← Back to MongoDB Course | Chapter 9: Schema Design | Lesson 3 of 7

Schema validation

Validation rules keep documents consistent even in a flexible schema.

In this page:

  1. Schema validation
Syntax
javascript
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

bash
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
  1. Skipping validation for critical collections
  2. Rules too strict to evolve
  3. Assuming validation checks existing data
Chapter Summary
  • $jsonSchema defines rules
  • validationLevel and validationAction tune it
  • collMod changes rules later
  • Applies on writes

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.