mongoose填充embedded式

我使用Mongoose.js并不能解决3级层次结构文件的问题。

有两种方法来做到这一点。

第一 – 没有参考。

C = new Schema({ 'title': String, }); B = new Schema({ 'title': String, 'c': [C] }); A = new Schema({ 'title': String, 'b': [B] }); 

我需要显示Clogging。 我怎么能填充/find它,只知道C的_id?

我曾尝试使用:

 A.findOne({'bc_id': req.params.c_id}, function(err, a){ console.log(a); }); 

但是我不知道如何从一个对象只得到我需要的对象。

其次,如果使用参考:

 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,Clogging以获得层次结构?

我试图使用这样的东西:

 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); }); }); }); }); 

但它会返回undefined为single_c.title。 我有办法填充它?

谢谢。

在Mongoose 4中,您可以跨多个级别填充文档:

假设你有一个用户模式,跟踪用户的朋友。

 var userSchema = new Schema({ name: String, friends: [{ type: ObjectId, ref: 'User' }] }); 

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' } }); 

取自: http : //mongoosejs.com/docs/populate.html#deep-populate

从Mongoose 3.6开始,添加了在查询中recursion填充相关文档的function。 这里是你如何做的一个例子:

  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'。

注意第二个(内部)填充 – 这是魔术发生的地方。 您可以继续嵌套这些填充并粘贴越来越多的文档,直到您按照需要的方式构build了graphics。

消化这个工作是需要一点时间的,但是如果你通过这个工作,这是有道理的。

在Mongoose 4中,您可以像这样填充多级(即使在不同的数据库或实例中)

 A .find({}) .populate({ path: 'b', model: 'B', populate: { path: 'c', model: 'C' } }) .exec(function(err, a){}); 

我迟到了,但我写了一个Mongoose插件 ,使得执行深度模型人口变得非常简单。 对于你的例子,你可以这样做来填充bc

 A.find({}, function (err, docs) { A.deepPopulate(docs, 'b.c', cb) } 

您也可以为每个填充path指定Mongoose填充选项 ,如下所示:

 A.deepPopulate(docs, 'b.c', { b: { select: 'name' } }, cb) 

查看插件文档以获取更多信息。