Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validated array of objects using mongodb validator?

I have been trying to validate my data using the validators provided by MongoDB but I have run into a problem. Here is a simple user document which I am inserting.

{
    "name"    : "foo",
    "surname" : "bar",
    "books"   : [
      {
        "name" : "ABC",
        "no"   : 19
      },
      {
        "name" : "DEF",
        "no"   : 64
      },
      {
        "name" : "GHI",
        "no" : 245
      }
    ]
}

Now, this is the validator which has been applied for the user collection. But this is now working for the books array which I am inserting along with the document. I want to check the elements inside the object which are the members of books array. The schema of the object won't change.

db.runCommand({
  collMod: "users",
  validator: {
    $or : [
      { "name"       : { $type : "string" }},
      { "surname"    : { $type : "string" }},
      { "books.name" : { $type : "string" }},
      { "books.no"   : { $type : "number" }}
    ],
  validationLevel: "strict"
});

I know that this validator is for member objects and not for array, but then how do I validate such an object ?

like image 786
molecule Avatar asked Mar 10 '23 05:03

molecule


1 Answers

It has been very long since this question was asked.
Anyways, if at all anyone comes through this.

For MongoDB 3.6 and greater version, this can be achieved using the validator.


 db.createCollection("users", {
    validator: {
       $jsonSchema: {
          bsonType: "object",
          required: ["name","surname","books"],
          properties: {
            name: {
                bsonType: "string",
                description: "must be a string and is required"
             },    
             surname: {
                bsonType: "string",
                description: "must be a string and is required"
             },         
             books: {
                bsonType: [ "array" ],
                items: {
                    bsonType: "object",
                    required:["name","no"],
                    properties:{
                        name:{
                            bsonType: "string",
                            description: "must be a string and is required"
                        },
                        no:{
                            bsonType: "number",
                            description: "must be a number and is required"
                        }
                    }
                },
                description: "must be a array of objects containing name and no"
             }
          }
       }
    }
 })

This one handles all your requirements.
For more information, refer this link

like image 113
saintlyzero Avatar answered Mar 13 '23 09:03

saintlyzero