2015-10-03 75 views
2

如何填充参考文档中子文档,这是我的架构:如何填充的子文档的参考(猫鼬)

var person = mongoose.Schema({ 
    name: { type: [String], index: true }, 
    career: [{ 
     position: { type: mongoose.Schema.Types.ObjectId, ref: 'Orgchart' } 
    }] 
}; 

var orgchart = mongoose.Schema({ 
     name: { type: [String], index: true }, 
}; 

我用这部分尝试:

person.find({ _id: "12345" }).populate('orgchart').exec(function(err, data){ 
    res.send(data); 
}); 

我得到了错误Cannot read property 'name' of undefined当我打电话给玉模板

item.career._orgchart.name 

回答

3

您需要将字段的点符号路径名传递给弹出乌拉特到populate电话:

person.find({ _id: "12345" }).populate('career.position').exec(function(err, data){ 
    res.send(data); 
}); 

不知道为什么你试图从玉访问此使用_orgchart,因为它是一个将与引用orgchart文档来填充career数组的元素在同一个position领域。

0

由于JohnnyHK先生

我用:

person.findOne({ _id: req.params.person }).populate('career.position career.grade').exec(function(err, data){ 
    res.send(data); 
}); 

我在循环使用的数据对item.position.name玉模板

感谢