如何指定总共三个字段中至少需要一个字段?
How to specify that at least one field is required out of three in total?
在我的MongoDB模型中,总共有3个字段。添加到此集合的任何文档必须至少包含这 3 个字段中的 1 个。
如何在分阶段验证中指定?
您可以枚举创建集合的验证约束,如下所示:
db.createCollection("jobs", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "status" ],
properties: {
status: {
enum: [ "Done", "Failed", "Initial" ],
description: "can only be one of the enum values and is required"
},
}
}
}
})
来自docs
Mongoose 有几个内置的验证器。字符串将枚举作为验证器之一。因此 enum 创建了一个验证器并检查该值是否在数组中给出。例如:
var userSchema = new mongooseSchema({
status: {
type: String,
enum : ['Done','Failed', 'Initial'],
default: 'Initial'
},
})
您可以使用自定义验证器来检查对象中是否有 3 个键之一
const testSchema = mongoose.Schema({
field1: {
type: String,
validate: {
validator: function(v) {
if (this.field2 == undefined && this.field3 == undefined) {
return true;
}
return false;
},
},
},
field2: {
type: String,
validate: {
validator: function(v) {
if (this.field1 == undefined && this.field3 == undefined) {
return true;
}
return false;
},
},
},
field3: {
type: String,
validate: {
validator: function(v) {
if (this.field2 == undefined && this.field1 == undefined) {
return true;
}
return false;
},
},
},
});
在我的MongoDB模型中,总共有3个字段。添加到此集合的任何文档必须至少包含这 3 个字段中的 1 个。
如何在分阶段验证中指定?
您可以枚举创建集合的验证约束,如下所示:
db.createCollection("jobs", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "status" ],
properties: {
status: {
enum: [ "Done", "Failed", "Initial" ],
description: "can only be one of the enum values and is required"
},
}
}
}
})
来自docs
Mongoose 有几个内置的验证器。字符串将枚举作为验证器之一。因此 enum 创建了一个验证器并检查该值是否在数组中给出。例如:
var userSchema = new mongooseSchema({
status: {
type: String,
enum : ['Done','Failed', 'Initial'],
default: 'Initial'
},
})
您可以使用自定义验证器来检查对象中是否有 3 个键之一
const testSchema = mongoose.Schema({
field1: {
type: String,
validate: {
validator: function(v) {
if (this.field2 == undefined && this.field3 == undefined) {
return true;
}
return false;
},
},
},
field2: {
type: String,
validate: {
validator: function(v) {
if (this.field1 == undefined && this.field3 == undefined) {
return true;
}
return false;
},
},
},
field3: {
type: String,
validate: {
validator: function(v) {
if (this.field2 == undefined && this.field1 == undefined) {
return true;
}
return false;
},
},
},
});