jsonSchema working only for the first item of an array of objects

I also replied to your SO post.

The array assertions are at the wrong level.

One thing to note is the use of additionalProperties:false causes a validation error with MongoDB schemas if you don’t define _id in your schema definition. This is because all documents are inserted with _id by default if you omit this property from your document insertion.

source: https://www.mongodb.com/docs/manual/core/schema-validation/specify-json-schema/json-schema-tips/#_id-field-and-additionalproperties--false

db.createCollection("colors", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            title: "Colors Available",
            required: ["colors_available"],
            properties: {
                "colors_available": {
                    "bsonType": "array",
                    "minItems": 1,
                    "uniqueItems": true,
                    "items": {
                        "bsonType": "object",
                        "additionalProperties": false,
                        "required": [
                            "color",
                            "stock"
                        ],
                        "properties": {
                            "_id": {
                                "bsonType": "objectId"
                            },
                            "color": {
                                "bsonType": "string"
                            },
                            "stock": {
                                "bsonType": "int"
                            }
                        }
                    }
                }
            }
        }
    }
})

The example you provided has an error in the second schema "color:". The colon should be outside of the quotes.

A valid payload for this schema follows:

db.colors.insertOne({
    "colors_available": [
        {
          "color": "Green",
          "stock": 42
        },
        {
          "color": "Black",
          "stock": 13
        },
        {
          "color": "White",
          "stock": 21
        }
      ]
    
 })
1 Like