javascript - 如何验证 mongodb 模式中的列表?

标签 javascript json mongodb jsonschema

我正在创建 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 有 documentation on $jsonSchema但您可以在 JSON Schema validation spec 中找到更多详细信息链接到 MongoDB 文档。

关于javascript - 如何验证 mongodb 模式中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549803/

相关文章:

javascript - Python urllib2.unquote() 与 Javascript unescape()

javascript - 如何解决 C :\fakepath?

javascript - NodeJS - 将变量发送到客户端

ios - 在 Swift 中使用 Alamofire 5.0 获取 3 级深度 JSON 值

javascript - 我可以将 css 语法添加到 select2 的 "text"属性中吗?

mongodb - MongoDB 3.0 中的“无法取消链接套接字文件”错误

mongodb - 如何告诉 MongoDB C# 驱动程序以字符串格式存储所有 Guid?

javascript - 在node.js中做一系列的异步操作

java - 来自 JSON 的通知服务

arrays - 如何统计mongodb中数组元素出现的次数?