2016-08-24 147 views
0

我使用的猫鼬和的NodeJS具有架构是这样的:自我的猫鼬填充

var category = new Schema({ 
     name: String, 
     parent: [{ type: ObjectId, ref: 'category', default: null }] 
    }); 

和类别收集我有2个文件这样 文件1:

{ 
    "_id" : "d3d4c44r43ce4366f563fg", 
    "name" : "document 1", 
    "parent" : null 
} 

文件2:

{ 
    "_id" : "d3d4c65ygyb779676768p54", 
    "name" : "document 1", 
    "parent" : "d3d4c44r43ce4366f563fg" 
} 

我如何从文档1中使用填充猫鼬获取所有的孩子。

回答

0

如果你知道你想要的父母,你可以这样做:

查找与所需的父ID(parent_id)和populate孩子使用populate('parent')

//Assuming you know the parent id to populate (parent_id) 
category.find({parent : parent_id}).populate('parent').exec(function(err,docs){...}); 

编辑:优生优育所有文件的父母都是NULL

首先,找到所有文件的parentnull。并为每一个,populate采用上述方法收集。

category.find({parent:null},function(err,results) 
{ 
    if(!err) 
    { 
     //for each parent, populate their children. 
     results.forEach(result,index,array) 
     { 
      //result._id is the parent id, use this to retrieve its child 
      category.find({parent : result._id}).populate('parent').exec(function(err,docs) 
      { 
       //use these docs however you want to use. 
       //For every parent different `docs` array will be there. 
      }); 
     } 
    } 
}); 
+0

我想让所有类别的所有子类都有父字段为空 –