我是mongodb的新手,想要使用查找
填充两个ID例如:
{
"sampleId1": "5kjksds8nkjfhsjfi8kl",
"sampleId2": "7jhjshfi9jsfkjsdfkkk"
}
我正在使用聚合框架来查询数据,并希望将两个ID都打开。
我希望$loopup
填充与
Model.find().populate('sampleId1').populate('sampleId2')
答案 0 :(得分:0)
对于您的情况,我想建议您mongoose-autopopulate这样
const autopopulate = require('mongoose-autopopulate')'
const sampleSchema = new Schema({
sampleId1: {type: Schema.ObjectId, ref: 'ColleactionName', autopopulate: {select: 'firstName, lastName'}},
sampleId2: {type: Schema.ObjectId, ref: 'ColleactionName', autopopulate: {select: 'firstName, lastName'}}
})
sampleSchema.plugin(autopopulate)
module.exports = mongoose.model('sampleSchema', sampleSchema)
现在,无论何时您请求查找,它都会自动填充所有字段 谁拥有
Schema.ObjectId
let criteria = {},
projection = {},
options = {lean: true}
Model.find(criteria, projection, options, (err, result) => {
console.log(result); // See out-put
})
您需要在架构中检查第二件事,即sampleId1和sampleId2都具有类型type: Schema.ObjectId
,并引用了集合名称ref: 'ColleactionName'
你已经做过这件事的第二种方式问题
sampleSchema.
find(...).
populate('sampleId1').
populate('sampleId2').
exec();