Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to validate data in mongo?

What's the best way to validate data being inserted or updated into MongoDB? Is it to write some sort of server executed Javascript code that does the validation?

like image 508
Simon Wentley Avatar asked Feb 13 '10 22:02

Simon Wentley


1 Answers

Starting MongoDB 3.6 you can also use JSON Schema to express validation rules. These checks will happen on the database side on insert/update.

Here is an example from the docs:

   validator = {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "address" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
               enum: [ "Math", "English", "Computer Science", "History", null ],
               description: "can only be one of the enum values and is required"
            },
            gpa: {
               bsonType: [ "double" ],
               description: "must be a double if the field exists"
            },
            address: {
               bsonType: "object",
               required: [ "city" ],
               properties: {
                  street: {
                     bsonType: "string",
                     description: "must be a string if the field exists"
                  },
                  city: {
                     bsonType: "string",
                     description: "must be a string and is required"
                  }
               }
            }
         }
      }
   }
db.runCommand( {
   collMod: "collectionName",
   validator: validator
} )
like image 73
Katya Kamenieva Avatar answered Sep 30 '22 20:09

Katya Kamenieva