【发布时间】:2020-05-22 00:57:42
【问题描述】:
问题: 我想为具有动态参考和直接参考另一个模型的模型实现猫鼬的内部连接。请参考下面的示例架构和模型。
const schema1 = mongoose.schema({
on: {
type: Schema.Types.ObjectId,
required: true,
refPath: 'onModel'
},
onModel: {
type: String,
required: true,
enum: ['Model2', 'Model3']
},
company: {
type: Schema.Types.ObjectId,
ref: 'Company'
}
});
const Model1 = mongoose.model('Model1', schema1);
const schema2 = mongoose.schema({
name: {
type: String,
maxlength: 100
},
email: {
type: String,
maxlength: 100
}
});
const Model2 = mongoose.model('Model2', schema2);
const schema3 = mongoose.schema({
name: {
type: String,
maxlength: 100
},
email: {
type: String,
maxlength: 100
}
});
const Model3 = mongoose.model('Model3', schema3);
const companySchema = mongoose.schema({
companyName: {
type: String,
maxlength: 100
}
});
const company = mongoose.model('Company', companySchema);
const res = await models.Model1
.find()
.populate({
path: 'on',
match: {
'name': keyword
}
})
.populate({
path: 'company',
match: {
'companyName': keyword
}
});
上面的 find 会返回文档,即使 on 并且 company 返回 null 值(因为 mongoose populate 默认实现了左连接)。
预期结果:我想从模型 1 中获取文档,前提是它与模型 2 或模型 3 中的名称字段或公司模型中的公司名称字段匹配的关键字。
如何做到这一点?非常感谢您的帮助。
【问题讨论】:
标签: mongodb mongoose nosql inner-join