Articles → MONGODB → Validations In MongoDB

Validations In MongoDB






Purpose





Scenario




  1. Name should be mandatory
  2. Age should be non-negative

Creating A Collection With Validation




db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "age"],
      properties: {
        name: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        age: {
          bsonType: "int",
          minimum: 0,
          description: "must be a positive integer and is required"
        }
      }
    }
  }
})



Inserting Data




Picture showing inserting the invalid data in the users table
Click to Enlarge



Picture showing inserting the valid data in the users table
Click to Enlarge




Posted By  -  Karan Gupta
 
Posted On  -  Friday, July 28, 2023

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250