[英]How to validate list in mongodb schema?
我正在創建 HOME 集合驗證,其中我有房間類型(雙人間、單人間、套間),驗證應該允許添加列出的所有項目。
"rooms.type": {bsonType: ["ensuite", "double", "single"]},
這是我在驗證器中所擁有的
db.createCollection("home", {
validator : {
$jsonSchema : {
bsonType: "object",
required: ["address.line1", "address.town", "rooms.type",
"rooms.qty", "rooms.price"],
properties: {
"address.line1": {bsonType: "string"},
"address.town": {bsonType: "string"},
"rooms.type": {bsonType: ["ensuite", "double", "single"]},
"rooms.qty": {bsonType: "int", minimum: 0},
"rooms.price": {bsonType: ["double"], minimum: 0},
}}}})
我收到一個錯誤
"ok" : 0,
"errmsg" : "Unknown type name alias: ensuite",
"code" : 2,
"codeName" : "BadValue"
我希望數組 room.type 允許模式中指定的組中的一個或所有屬性。
您可以指定rooms.type
的類型應該是“數組”,數組中至少有1個項目,並且該數組的每個項目都應該是一個枚舉,如下所示:
"rooms.type": {
type: "array",
minItems: 1,
items: {
enum: ["ensuite", "double", "single"]
}
}
MongoDB 有關於 $jsonSchema 的文檔,但您可以在鏈接到 MongoDB 文檔的JSON Schema 驗證規范中找到更多詳細信息。
您還可以通過以下方式指定架構:
db.createCollection('home', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['address', 'rooms'],
properties: {
address: {
bsonType: 'object',
additionalProperties: false,
required: ['line1', 'town'],
properties: {
line1: {
bsonType: 'string'
},
town: {
bsonType: 'string'
}
}
},
rooms: {
bsonType: 'object',
additionalProperties: false,
required: ['type', 'qty', 'price'],
properties: {
type: {
bsonType: 'string',
enum: ["ensuite", "double", "single"]
},
qty: {
bsonType: 'int',
minimum: 0
},
price: {
bsonType: 'array',
items: {
bsonType: 'double',
minimum: 0
}
}
}
}
}
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.