Problem Statement
How can you enforce schema validation in MongoDB?
Explanation
MongoDB allows you to enforce schema validation rules using JSON Schema syntax when creating or modifying collections. While MongoDB is schema-less by default, validation rules ensure data integrity by rejecting documents that do not match the specified schema.
You can set validation level to strict to reject invalid documents or moderate to allow existing invalid documents but reject new ones. Validation action can be error to reject invalid documents or warn to log warnings but allow them.
Code Solution
SolutionRead Only
// Create collection with schema validation
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "age"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "must be a valid email"
},
age: {
bsonType: "int",
minimum: 18,
maximum: 120
}
}
}
},
validationLevel: "strict",
validationAction: "error"
})