【问题标题】:How to validate list in mongodb schema?如何验证 mongodb 模式中的列表?
【发布时间】:2019-04-06 13:59:27
【问题描述】:

我正在创建 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 允许架构中指定的组中的一个或所有属性。

【问题讨论】:

    标签: javascript json mongodb jsonschema


    【解决方案1】:

    您可以指定rooms.type 的类型应为“数组”,数组中至少包含一项,并且该数组的每个项都应为枚举,如下所示:

    "rooms.type": {
        type: "array",
        minItems: 1,
        items: {
            enum: ["ensuite", "double", "single"]
        }
    }
    

    MongoDB 有 documentation on $jsonSchema,但您可以在 MongoDB 文档链接的 JSON Schema validation spec 中找到更多详细信息。

    【讨论】:

    • 感谢您的帮助;该解决方案有效。请问您在哪里可以找到更多类似的信息?
    • 添加了几个链接,不幸的是他们没有很好的例子
    【解决方案2】:

    您也可以通过这种方式指定架构:

    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
                  }
                }
              }
            }
          }
        }
      }
    });
    
    

    【讨论】:

    • 谢谢,这是很好的定义模式。将在我的项目中使用。
    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 2018-03-20
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    相关资源
    最近更新 更多