如何确保在mongoDB中只填充两个字段中的一个



我正在使用猫鼬作为ODM,并尝试为动物/宠物建模。在模型中,我有两个字段,父字段和避难所。我想确保宠物属于一个人或一个收容所,但不能同时属于两者。什么样的限制条件允许我这样做。

我在JS中的模型:-

const petSchema = mongoose.Schema({
name: { 
type: String,
required: [true, "Pet must have a name."],
trim: true
},
species: {
type: String,
required: [true, "Pet must have a species."]
},
parent: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
shelter: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Shelter'
}
}

我是数据库及其术语的新手,如果有任何错误,请纠正我。非常感谢。

您可以使用所需的函数来确定如下:

const petSchema = mongoose.Schema({
name: { 
type: String,
required: [true, "Pet must have a name."],
trim: true
},
species: {
type: String,
required: [true, "Pet must have a species."]
},
parent: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: function() {
return !this.shelter;
}
},
shelter: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Shelter',
required: function() {
return !this.parent;
}
}
}

我最终在mongoose中使用了预验证中间件:-

petSchema.pre('validate', function (next) {
if((this.parent && this.shelter) || (!this.parent && !this.shelter))
return next(new Error("At least and Only one field(parent, shelter) should be populated"))
next()
})

最新更新