mongodb json 独立验证无效 mongo

mongodb json validation is not working in standalone mongo

我有独立的 mongo 设置,我添加了包含所有验证的集合脚本,但验证不起作用..所以尝试了这个 mongo guide,并执行了类似的步骤,但验证不起作用。它正在接受文档。

我执行了以下收集脚本

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" ],
               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"
            }
         }
      }
   },
   validationLevel: "strict",
validationAction: "error"
})

然后执行以下查询。

db.students.insert({
   name: "Alice",
   year: NumberInt(2019),
   major: "History",
   gpa: NumberInt(3),
   address: {
      city: "NYC",
      street: "33rd Street"
   }
})

得到低于响应

WriteResult({ "nInserted" : 1 })

但我期待验证错误。

WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 121,
      "errmsg" : "Document failed validation"
   }
})

我需要在 mongodb 设置中启用某些功能吗?

我的mongo版本是

MongoDB shell version v3.4.18

您需要将“gpa: NumberInt(3)”行替换为“gpa:3”

 db.students.insert({
   name: "Alice",
   year: NumberInt(2019),
   major: "History",
   gpa: 3,
   address: {
      city: "NYC",
      street: "33rd Street"
   }
})

希望有用