Ole*_*tor 31 javascript mongoose mongodb nosql node.js
我使用Mongoose.js并不能解决3级层次文档的问题.
有两种方法可以做到这一点.
首先 - 没有参考.
C = new Schema({
'title': String,
});
B = new Schema({
'title': String,
'c': [C]
});
A = new Schema({
'title': String,
'b': [B]
});
Run Code Online (Sandbox Code Playgroud)
我需要显示C记录.我怎么能填充/找到它,只知道C的_id?
我试着用:
A.findOne({'b.c._id': req.params.c_id}, function(err, a){
console.log(a);
});
Run Code Online (Sandbox Code Playgroud)
但是我不知道如何从者返回一个只有我需要的对象的对象.
第二,如果使用refs:
C = new Schema({
'title': String,
});
B = new Schema({
'title': String,
'c': [{ type: Schema.Types.ObjectId, ref: 'C' }]
});
A = new Schema({
'title': String,
'b': [{ type: Schema.Types.ObjectId, ref: 'B' }]
});
Run Code Online (Sandbox Code Playgroud)
如何填充所有B,C记录以获得层次结构?
我试着用这样的东西:
A
.find({})
.populate('b')
.populate('b.c')
.exec(function(err, a){
a.forEach(function(single_a){
console.log('- ' + single_a.title);
single_a.b.forEach(function(single_b){
console.log('-- ' + single_b.title);
single_b.c.forEach(function(single_c){
console.log('--- ' + single_c.title);
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
但它将为single_c.title返回undefined.我有办法填充它吗?
谢谢.
Box*_*cks 42
从Mongoose 3.6 开始,添加了在查询中递归填充相关文档的能力.以下是如何执行此操作的示例:
UserList.findById(listId)
.populate('refUserListItems')
.exec(function(err, doc){
UserListItem.populate(doc.refUserListItems, {path:'refSuggestion'},
function(err, data){
console.log("User List data: %j", doc);
cb(null, doc);
}
);
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我使用引用的文档填充'refUserListItems'中的id数组.然后查询的结果将传递到另一个填充查询,该查询引用我想要填充的原始填充文档的字段 - 'refSuggestion'.
注意第二个(内部)填充 - 这是神奇发生的地方.您可以继续嵌套这些填充并粘贴越来越多的文档,直到您以所需的方式构建图形.
它需要一点时间来消化它是如何工作的,但如果你通过它,它是有道理的.
Tri*_*Nhu 30
在Mongoose 4中你可以像这样填充多级(即使在不同的数据库或实例中)
A
.find({})
.populate({
path: 'b',
model: 'B',
populate: {
path: 'c',
model: 'C'
}
})
.exec(function(err, a){});
Run Code Online (Sandbox Code Playgroud)
Gia*_* P. 29
在Mongoose 4中,您可以跨多个级别填充文档:
假设您有一个用户模式,可以跟踪用户的朋友.
var userSchema = new Schema({
name: String,
friends: [{ type: ObjectId, ref: 'User' }]
});
Run Code Online (Sandbox Code Playgroud)
首先populate(),您可以获得用户朋友列表.但是,如果您还想要用户的朋友朋友呢?在这种情况下,您可以指定一个populate选项来告诉mongoose填充friends所有用户朋友的数组:
User.
findOne({ name: 'Val' }).
populate({
path: 'friends',
// Get friends of friends - populate the 'friends' array for every friend
populate: { path: 'friends' }
});
Run Code Online (Sandbox Code Playgroud)
取自:http://mongoosejs.com/docs/populate.html#deep-populate
我迟到了,但我写了一个Mongoose 插件,它使得执行深度模型填充变得非常简单。对于您的示例,您可以这样做来填充b和c:
A.find({}, function (err, docs) {
A.deepPopulate(docs, 'b.c', cb)
}
Run Code Online (Sandbox Code Playgroud)
您还可以为每个填充的路径指定Mongoose 填充选项,如下所示:
A.deepPopulate(docs, 'b.c', {
b: {
select: 'name'
}
}, cb)
Run Code Online (Sandbox Code Playgroud)
查看插件文档以获取更多信息。