我使用 Mongoose.js,无法解决 3 级层次文档的问题。
有两种方法。
第一 - 没有引用。
C = new Schema({
'title': String,
});
B = new Schema({
'title': String,
'c': [C]
});
A = new Schema({
'title': String,
'b': [B]
});
我需要显示 C 记录。我如何填充/找到它,只知道 C 的 _id?
我正在尝试使用:
A.findOne({'b.c._id': req.params.c_id}, function(err, a){
console.log(a);
});
但我不知道如何从 returnet 中获取我需要的仅 c 对象。
其次如果使用 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' }]
});
如何填充所有 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);
});
});
});
});
但它会为 single_c.title 返回 undefined。我有办法填充它吗?
谢谢。
最佳答案
从 Mongoose 3.6 开始 the ability to recursively populate related documents在查询中已添加。以下是您可以如何做到的示例:
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);
}
);
});
在这种情况下,我在 'refUserListItems' 中使用他们引用的文档填充一个 id 数组。然后,查询的结果会被传递到另一个填充查询,该查询引用我想要填充的原始填充文档的字段 - 'refSuggestion'。
注意第二个(内部)填充 - 这就是魔法发生的地方。您可以继续嵌套这些填充并添加越来越多的文档,直到按照您需要的方式构建图表。
这需要一点时间来消化它是如何工作的,但如果你通过它,它是有意义的。
关于javascript - Mongoose 填充嵌入式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13077609/