在我的 MongoDB 模型中,總共有 3 個欄位。添加到此集合的任何檔案必須至少包含這 3 個欄位中的 1 個。
如何在驗證階段中指定這一點?
uj5u.com熱心網友回復:
您可以列舉驗證約束哪個集合創建如下:
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"
},
}
}
}
})
從檔案
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;
},
},
},
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/454906.html
