MongoDB Schema Validation

MongoDB Schema Validation 🛡️📐
It helps prevent bad/invalid data from being inserted or updated.
Why Schema Validation?
Ensure data consistency
Catch invalid inserts/updates
Enforce required fields & data types
Safer for large teams & production apps
📌 Validation is applied at the collection level.
Ways to Define Schema Validation
MongoDB supports:
JSON Schema (
$jsonSchema) ✅ (Know this)Query Expression Validators (older style)
👉 Prefer JSON Schema (clear & standard).
1️⃣ Create Collection with Schema Validation (JSON Schema)
Example: students collection
✅ Collection created with validation rules.
2️⃣ Insert Valid Document ✅
✔ Insert succeeds.
3️⃣ Insert Invalid Document ❌
❌ Fails due to:
age < 18
course not allowed
4️⃣ Validation Levels
validationLevel
strict (default) → validate all inserts & updates
moderate → validate only new/updated fields
5️⃣ Validation Actions
validationAction
error (default) → reject invalid data
warn → allow insert but log warning
6️⃣ Modify Validation on Existing Collection
7️⃣ Schema Validation Using Query Expressions (Alternative)
⚠️ Less readable than JSON Schema.
MongoDB vs SQL Schema
| SQL | MongoDB |
|---|---|
| Strict schema | Flexible schema |
| Defined in table | Defined via validator |
| ALTER TABLE | collMod |
Best Practices 👍
Use schema validation in production
Start with moderate, move to strict
Combine with indexes
Validate only critical fields
Common Mistakes ❌
Forgetting
bsonType(use BSON types, not JS types)Over-validating (kills flexibility)
Expecting validation to fix old data
