使用验证规则更新mongodb集合时,如何禁止未知属性?

时间:2018-12-28 14:46:15

标签: mongodb

这是https://stackoverflow.com/posts/38101932的副本 但是由于答案是过时的,所以链接的“解决方案”不是直接的答案,因此我将其再次发布。

我想禁止架构中未声明的其他属性。例如,如果架构显示:

"group1.a": {
  "$type": "int"
},
"group1.b": {
  "$type": "int"
}

我希望以下文档失败:

{
   "group1": {
      "a": 1,
      "b": 2,
      "c": 3
   }
}

我究竟如何利用jsonShema来完成这项工作?

2 个答案:

答案 0 :(得分:0)

找到了!

必须完成两件事:

  1. additionalProperties: false添加到$jsonSchema
  2. 使用_id作为显式属性添加bsonType: objectId字段,否则每次更新都会失败(除非在向集合中插入新文档时未显式设置_id)。

答案 1 :(得分:-1)

来自the docs on schema validationjsonSchema

以下面的示例为例,添加可选属性:additionalProperties: false

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "gpa", "address.city", "address.street" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            gender: {
               bsonType: "string",
               description: "must be a string and is not required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               exclusiveMaximum: false,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
               enum: [ "Math", "English", "Computer Science", "History", null ],
               description: "can only be one of the enum values and is required"
            },
            gpa: {
               bsonType: [ "double" ],
               minimum: 0,
               description: "must be a double and is required"
            },
            "address.city" : {
               bsonType: "string",
               description: "must be a string and is required"
            },
            "address.street" : {
               bsonType: "string",
               description: "must be a string and is required"
            }
         }
      }
   }
})

相关的开发票上还有一些其他可用的读物:https://jira.mongodb.org/browse/SERVER-30191