【发布时间】:2016-05-31 05:22:45
【问题描述】:
我正试图围绕 Mongoose Populate 语法和结构展开思考。我有两个模式。 Parent 有一个 Child 引用数组。
const Parent = new Schema({
name: String,
children: [{type: Schema.ObjectId, ref: 'Child'}]
});
const Child = new Schema({
name: String
});
为了填充 Parent 我一直在这样做:
Parent
.findById(parent.id)
.populate('children')
.exec( (err, parent) => {
parent.children = arrayOfInsertedChildDocs;
parent.save();
});
Parent 引用保存,但有没有办法查询具有某个 Child 引用的 Parents?例如,所有在其 children 数组中引用 ID 为 ObjectId('xxxxxxxxx') 的孩子的父母?
这是我一直在尝试的,但它不起作用。
let query = { "children._id": mongoose.Types.ObjectId(childId) };
Parent.find(query, (err, parents) => {
//process parents
})
这可能吗?
【问题讨论】:
标签: node.js mongodb mongoose mongodb-query mongoose-populate