mongoose,arrays模型上的深度人口

我想深入填充一个可能过于复杂的模型

var ParentSchema = new Schema({ childs: [{type:Schema.ObjectId, ref: 'Child'}], }); var ChildSchema = new Schema({ subject: [{ price: {type: Number}, data: {type: Schema.ObjectId, ref: 'Subject'} }] }) 

但是,当我使用正规人群时似乎并不奏效。 我现在安装深度填充,并使用以下内容:

 Parent.deepPopulate('childs.subjects'); 

我想知道是否有一个更简单的方法来完成一个人口众多的主题。

mongoose深度填充的插件将为此工作,但你需要使用正确的path到你想填充的最深的领域。 在这种情况下,查询应该如下所示:

 Parent.findOne().deepPopulate('childs.subject.data').exec(function(err, parents) {...}); 

然而,意识到这一点很重要,即使用多个查询(至less每个人口级别一个)来执行人口。 首先是Parent查询,然后是Child查询,然后是Subject查询。 因此,尽可能embedded相关数据是最好的,但如果您需要独立查询子数据和主题数据,则这是不现实的。 所以如果你需要将你的相关文档分开collections,人口就是要走的路。

有关更多信息和指导,请参阅数据build模文档部分。

如果你不想使用deepPopulate插件,你可以做2遍:

  1. 填充孩子
  2. 填充subject.data

    它会生成3个请求(一个用于Parent,一个用于Child,另一个用于Subject)与deepPopulate插件一样:

 query = Parent.findOne().populate('childs'); query.exec(function(err, parent) { if (err) { //manage error }; // now we need to populate all childs with their subject Child.populate(parent.childs, { path: 'subject.data', model: 'Subject' },function(err){ // parent object is completely populated }); });