Schema Validation
MongoDB's schema is flexible by default — but flexibility without guardrails can lead to inconsistent data. Schema validation lets you enforce structure and data integrity using JSON Schema, without giving up MongoDB's flexibility entirely.
1. Why Validate?
- Prevent malformed documents (missing required fields, wrong types)
- Catch bugs early — at the database layer, not just the application layer
- Document your schema intentions directly in the database
2. Creating a Collection with Validation
db.createCollection("employees", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "department"],
properties: {
name: { bsonType: "string", description: "must be a string and is required" },
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "must be a valid email address"
},
department: {
enum: ["Engineering", "Sales", "HR", "Marketing"],
description: "must be one of the enum values"
},
age: {
bsonType: "int",
minimum: 18,
maximum: 65,
description: "must be an integer between 18 and 65"
}
}
}
}
})
3. Validation Levels and Actions
| Option | Values | Effect |
|---|---|---|
validationLevel | "strict" (default) / "moderate" | Strict validates all writes; moderate skips existing invalid documents |
validationAction | "error" (default) / "warn" | Error rejects invalid writes; warn logs but allows them |
4. Adding Validation to an Existing Collection
db.runCommand({
collMod: "employees",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"]
}
},
validationLevel: "moderate"
})
Common Issue: Applying strict validation to a collection with existing "bad" documents will block future updates to those documents unless you use
validationLevel: "moderate".
5. Testing Validation
// This insert fails validation (missing required "department")
db.employees.insertOne({ name: "Kabir Singh", email: "kabir@example.com" })
// MongoServerError: Document failed validation
6. Schema Validation Checklist
- ✅ Define required fields and types with $jsonSchema
- ✅ Use enum for restricted value sets
- ✅ Choose validationLevel and validationAction appropriately
- ✅ Apply validation to existing collections with collMod
Key Takeaway: Schema validation gives you the best of both worlds — MongoDB's flexibility during development, with the safety of enforced structure as your application matures.
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.