Articles → MONGODB → Validations In MongoDB
Validations In MongoDB
Purpose
Scenario
- Name should be mandatory
- 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
db.users.insertOne({name:"gyan",age:-1})
Click to Enlarge
db.users.insertOne({name:"gyan",age:1})
Click to Enlarge