Schema validation
Validation rules keep documents consistent even in a flexible schema.
In this page:
Syntax
db.createCollection("collection_name", {
validator: { $jsonSchema: {
bsonType: "object",
required: ["field"],
properties: { field: { bsonType: "type" } }
} }
})
Schema validation
Use $jsonSchema in a collection validator to require fields, restrict types and set ranges or enums. Combine with validationLevel (strict or moderate) and validationAction (error or warn). Evolve rules with collMod as your model changes.
Note:
moderate validationLevel skips existing invalid documents when updating them.
Example: Schema validation
test> db.runCommand({
... collMod: "users",
... validator: { $jsonSchema: { bsonType: "object", required: ["email"], properties: { role: { enum: ["user", "admin"] } } } },
... validationLevel: "moderate", validationAction: "error"
... })
{ ok: 1 }
test> db.users.insertOne({ email: "[email protected]", role: "guest" })
MongoServerError: Document failed validation
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Skipping validation for critical collections
- Rules too strict to evolve
- Assuming validation checks existing data
Chapter Summary
- $jsonSchema defines rules
- validationLevel and validationAction tune it
- collMod changes rules later
- Applies on writes
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: