我有一个受害者模式:
let Victim= new Schema({
name: {type: String},
gender: {type: String},
Id: {type: String},
address: {type: String},
});
Culprit模式:
let Culprit= new Schema({
name: {type: String},
gender: {type: String},
cellphone: {type: String},
address: {type: String},
});
和案例架构:
let Case= new Schema({
victims:[String],//this contains array of victims _id's
culprits:[String],//this contains array of culprit _id's
aboutCase:{type:String},
caseType:{type:String},
date:{type:String}
})
请注意,案例模式的受害者字段包含受害者的_id,而罪魁祸首字段则包含数组的_id罪魁祸首。
现在,如果我这样做:
Case.find(function(err, allTheCases) {
if (err) {
console.log(err);
} else {
res.json(allTheCases);
//Question : How to get victims and culprits data as complete objects instead of just array of _id's
}
});
结果allTheCases
是所有Case对象的数组,其中每个对象都包含受害者字段。此受害者字段包含受害者_id的数组。
我的问题是:什么是正确的查询语法,所以最终结果(allTheCases
)将具有完整的受害者和罪魁祸首对象数组,而不仅仅是_id受害人和罪魁祸首的数组?
答案 0 :(得分:1)
您正在寻找的是$lookup
在mongodb聚合管道中
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
或者,如果您使用的是Mongoose ODM,则可以使用相应的方法populate必要字段:
let Case= new Schema({
victims:[{ type: Schema.Types.ObjectId, ref: 'Victim' }],
culprits:[{ type: Schema.Types.ObjectId, ref: 'Culprits'}],
aboutCase:{type:String},
caseType:{type:String},
date:{type:String}})
查询时:
Case.find().
populate('victims').
populate('culprits').
exec(function (err, cases) {
});