Javascript Mongoose-在对象中填充对象
假设我有3个型号:Javascript Mongoose-在对象中填充对象,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,假设我有3个型号: // Parent const ParentSchema = new Schema({ child: { type: ObjectId, ref: 'Child' }, ... }); // Child const ChildSchema = new Schema({ subChild: { type: ObjectId, ref: 'SubChild' },
// Parent
const ParentSchema = new Schema({
child: {
type: ObjectId,
ref: 'Child'
},
...
});
// Child
const ChildSchema = new Schema({
subChild: {
type: ObjectId,
ref: 'SubChild'
},
...
});
// SubChild
const SubChildSchema = new Schema({
name: String,
...
});
我在Parent
上使用findOne
,我想在Child
上使用populate
,但也在SubChild
上使用:
Parent.findOne(options)
.populate('child', 'subChild')
// Trying to add another populate on subChild property like : .populate('<above_subChild>', 'name')
.select('child')
.exec(function (err, parent) {
callback(err, parent.toJSON());
})
;
下面是我希望通过在subChild
属性上添加另一个populate
得到的结果:
{
// Parent _id
_id: XXX,
child: {
_id: XXX,
subChild: {
_id: XXX,
name: XXX
}
}
}
参考的文档,为了填充多个级别,查询需要按如下方式进行结构:
Parent.findOne(选项)
.填充({
路径:'子',
填充:{
路径:“子孩子”
}
})
.select('子')
.exec(函数(错误,父级){
回调(err,parent.toJSON());
});
使用mongoose的populate
方法需要注意的一点是,每个填充都需要单独的查询。因此,在本例中,虽然实现使用一个显式的findOne
方法,但mongoose实际上是连续执行三个查询
这大致相当于(稍微伪编码):
Parent.findOne().exec()。然后((Parent)=>([
父母亲
Child.findById(parent.Child.exec())
])).然后(([父,子])=>([
父母亲
小孩
SubChild.findById(child.SubChild.exec())
]))。然后(([父、子、子子女])=>{
child.subChild=subChild;
parent.child=child;
返回父母;
});
参考的文档,查询需要按以下结构填充多个级别:
Parent.findOne(选项)
.填充({
路径:'子',
填充:{
路径:“子孩子”
}
})
.select('子')
.exec(函数(错误,父级){
回调(err,parent.toJSON());
});
使用mongoose的populate
方法需要注意的一点是,每个填充都需要单独的查询。因此,在本例中,虽然实现使用一个显式的findOne
方法,但mongoose实际上是连续执行三个查询
这大致相当于(稍微伪编码):
Parent.findOne().exec()。然后((Parent)=>([
父母亲
Child.findById(parent.Child.exec())
])).然后(([父,子])=>([
父母亲
小孩
SubChild.findById(child.SubChild.exec())
]))。然后(([父、子、子子女])=>{
child.subChild=subChild;
parent.child=child;
返回父母;
});
这同样适用于:
Parent.findOne(options)
.select('child')
.populate('child.subChild')
.exec(function(err, parent) {
callback(err, parent.toJSON());
});
这也将起作用:
Parent.findOne(options)
.select('child')
.populate('child.subChild')
.exec(function(err, parent) {
callback(err, parent.toJSON());
});
我相信语法可能是
.populate(“子儿童”)
。如果只想填充一些字段,这是第二个参数.populate(“child subChild”,“name”)
@JeremyThille我可能不够精确,我将添加更多关于函数实际返回的内容以及预期结果的信息。我相信语法可能是.populate(“child subChild”)
。如果只想填充一些字段,这是第二个参数.populate(“child subChild”,“name”)
@JeremyThille我可能不够精确,我将添加更多关于函数实际返回的内容以及预期结果的信息。