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



这是 https://stackoverflow.com/posts/38101932 的副本但是由于那里的 anwser 已经过时并且链接的"解决方案"不是直接答案,我再次发布它。

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

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

我希望以下文档失败:

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

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

找到了!

必须做两件事:

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

来自有关架构验证和 jsonSchema 的文档:

以以下示例为例,添加可选属性: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

最新更新