我在 Mongoose 中创建了一个 Schema 模型,它具有多个属性,包括如下所示的属性。
所有这一切的问题在于,属性:名称、描述和国家/地区,仅应要求其中之一,而不是全部三个。
也就是说,如果我对这个模型进行 PUT,并且没有放置任何属性,则该模型无效,但是,如果我放置其中一个,则该模型是有效的(或者如果我放置两个,甚至三个)。
但是,此处所需的内容无效,因为它意味着添加三个属性。
我尝试过 required、validate 或 Mongoose 自己的钩子(Hook),但没有一个起作用。
const example = new Schema({
name: {
type: String,
required: true,
unique: true
},
description: String,
countries: {
type: [
{
type: String,
}
],
},
email: {
type: String
},
sex: {
type: String
},
});
我希望在满足要求的情况下,我始终需要这三个属性
最佳答案
您可以使用custom function作为所需属性的值。
const example = new Schema({
name: {
type: String,
required: function() {
return !this.description || !this.countries
},
unique: true
},
description: String,
countries: {
type: [
{
type: String,
}
],
},
email: {
type: String
},
sex: {
type: String
},
});
关于javascript - Mongoose 是否可以至少拥有一项所需的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57892491/