2016-08-24 199 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

我想讓所有類別的所有子類都有父字段爲空 –