Mongodb mongoose中如何实现内部连接
问题: 我想在mongoose中为一个模型实现一个内部连接,该模型具有对另一个模型的动态引用和直接引用。请参考下面的示例模式和模型Mongodb mongoose中如何实现内部连接,mongodb,mongoose,nosql,inner-join,Mongodb,Mongoose,Nosql,Inner Join,问题: 我想在mongoose中为一个模型实现一个内部连接,该模型具有对另一个模型的动态引用和直接引用。请参考下面的示例模式和模型 const schema1 = mongoose.schema({ on: { type: Schema.Types.ObjectId, required: true, refPath: 'onModel' }, onModel: { type: String, required: tru
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即使打开也会返回文档,company返回null值(因为mongoose填充默认实现左连接)
预期结果:仅当model1与model2或model3中的关键字with name字段或company model中的company name字段匹配时,我才希望从model1获取文档
如何做到这一点?非常感谢您的帮助。1.让我们更新“模型1”的模式,如下所示:-
const schema1=mongoose.schema( {
ref: {
kind: String, // <-- This will store the Model Name (Model2 or Model3) when you execute the insert query.
item: {
type: mongoose.Schema.Types.ObjectId, // <-- This will store the Reference ID of another table (Model2 OR Model3)
refPath: 'ref.kind', fields: String,
}
,
}
, company: {
type: Schema.Types.ObjectId, ref: 'Company'
}
});
它能帮助我实现内部连接吗?请澄清。但为什么它返回空值。您提到了required true,这意味着记录将存在于您的数据库中,并且您正在使用它作为引用。它返回null,因为此条件失败->匹配:{'name':keyword}
await models.Model1.find().populate({ path: 'ref.item' });