Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple JSON Schema validators per collection MongoDB

Tags:

mongodb

In MongoDB, I can set up a JSON Schema validation in a collection I create, such as these:

db.createCollection("teste", {
    validator: {
        jsonSchema: {
            bsonType: "object",
            required: ["campo1", "numero1"],
            properties: {
                campo1: {
                    bsonType: "string",
                    description: "Deve ser uma string"
                },
                numero1: {
                    bsonType: "string",
                    description: "Deve ser um texto"
                },
            }
        }
    }
})

But I have mixed-type collections that make use of the Polymorphic Pattern. Where I have something like five or more "types" of schema that are accepted in a collection.

Can I setup multiple JSON Schema validators in a collection? or just one?

like image 657
gtbono Avatar asked Oct 15 '25 18:10

gtbono


1 Answers

Yes, you can. $jsonSchema is just another query operator, you can use $or and $and the same way as you would in the filter:

{
  $or: [
    {
      $jsonSchema: {
        ...
      }
    },
    {
      $jsonSchema: {
        ...
      }
    }
  ]
}
like image 176
Katya Kamenieva Avatar answered Oct 18 '25 10:10

Katya Kamenieva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!