Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB jsonSchema validation additionalProperties

Tags:

mongodb

Create Collection with validator

db.createCollection("claims", 
    { validator : { $jsonSchema : { bsonType : "object", 
                 properties : { airportCode : { bsonType: "string"} }, 
                 additionalProperties: false} 
                  } } )

Insert db.claims.insert({"airportCode" : "DSM"}) => result: "errmsg" : "Document failed validation"

if I remove "additionalProperties: false" by creating the collection, when I can insert the document.

Any advice, how to keep "additionalProperties: false", because I want to control the document.

like image 413
Vikkes Avatar asked Jan 28 '18 21:01

Vikkes


1 Answers

As at MongoDB 3.6.2, JSON Schema validation does not automatically add the default _id property, so you need to include a rule for this when using additionalProperties: false.

For example, assuming the default ObjectID:

db.createCollection("claims",
    { validator : {
        $jsonSchema : {
            bsonType : "object",
            properties : {
                _id: { bsonType: "objectId" },
                airportCode : { bsonType: "string"}
            },
            additionalProperties: false
        }
     }}
)

Two related issues to upvote/watch on the MongoDB Jira issue tracker:

  • SERVER-32160: provide warning when _id is not in list of properties and additionalProperties is false
  • SERVER-20547: Expose the reason an operation fails document validation
like image 147
Stennie Avatar answered Sep 19 '22 16:09

Stennie