MongoDB Schema Validation

362 阅读1分钟

docs.mongodb.com/manual/core…是MongoDB后续推出的对collection的schema的结构校验功能,一般认为MongoDB是非结构型的数据库,数据结构灵活而随意,这样有好处也有坏处。当我们需要对某些关键性的表做结构约束时,那么这个功能可以用的上

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "address" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            year: {
               bsonType: "int",
               minimum: 1970,
               maximum: 2021,
               description: "must be an integer in [ 1970, 2021 ] 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 if the field exists"
            },
            address: {
               bsonType: "object",
               required: [ "city" ],
               properties: {
                  street: {
                     bsonType: "string",
                     description: "must be a string if the field exists"
                  },
                  city: {
                     bsonType: "string",
                     description: "must be a string and is required"
                  }
               }
            }
         }
      }
   }
})
think_db> show tables;
students
think_db> db.students.insertOne({
    "name":"thinkrik",
    "year":1993,
    "major":"Computer Science",
    "gpa":5.00000000001,
    "address":{
        "city":"Shenzhen",
        "street":"zhongshan yuan lu"
    }
    
})

{
  acknowledged: true,
  insertedId: ObjectId("61cddfba8745d233d7fc6be7")
}

think_db> db.students.insertOne({
    "name":"thinkrik",
    "year":2993,
    "major":"Computer Science",
    "gpa":5.00000000001,
    "address":{
        "city":"Shenzhen",
        "street":"zhongshan yuan lu"
    }
    
})
Uncaught:
MongoServerError: Document failed validation
Additional information: {
  failingDocumentId: ObjectId("61cde1a08745d233d7fc6bf1"),
  details: {
    operatorName: '$jsonSchema',
    schemaRulesNotSatisfied: [
      {
        operatorName: 'properties',
        propertiesNotSatisfied: [ { propertyName: 'year', details: [ [Object] ] } ]
      }
    ]
  }
}