Vikkes
Vikkes

Reputation: 548

MongoDB jsonSchema validation additionalProperties

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.

Upvotes: 12

Views: 3668

Answers (1)

Stennie
Stennie

Reputation: 65363

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:

Upvotes: 21

Related Questions