如何确保 mongoDB 中只填充了两个字段之一
How to make sure that only one of two fields are populated in mongoDB
我正在使用 mongoose 作为 ODM 并尝试为 animal/pet 建模。在模型中,我有 2 个字段,parent 和 shelter。我想确保宠物属于一个人或一个收容所,但不能同时属于两者。哪些限制允许我这样做。
我在 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()
})
我正在使用 mongoose 作为 ODM 并尝试为 animal/pet 建模。在模型中,我有 2 个字段,parent 和 shelter。我想确保宠物属于一个人或一个收容所,但不能同时属于两者。哪些限制允许我这样做。
我在 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()
})