Chapter 23: MongoDB Schema Validation

MongoDB Schema Validation β€οΈπŸ“œ

Up to now we enjoyed the freedom of MongoDB being schemaless β€” you can throw any document you want into any collection, different documents can have completely different fields, no problem.

But in real production applications (especially when multiple developers or multiple services write to the same collection), this freedom becomes dangerous.

  • Someone accidentally writes “age”: “twenty five” instead of number 25
  • Someone forgets to include “email” which your application assumes always exists
  • Someone writes “status”: “activee” (typo) instead of “active”
  • Someone puts “price”: -500 when price should never be negative

β†’ Chaos. Bugs. Angry users. Late-night debugging.

Schema Validation is MongoDB’s way of saying:

β€œOkay, you can still be flexible… but not completely lawless. Let me enforce some basic rules so the data stays clean, consistent and safe.”

1. What Exactly is Schema Validation?

Schema validation is a collection-level rule that MongoDB enforces every time someone tries to insert or update a document in that collection.

  • You define the rules when you create the collection (or later with collMod)
  • Rules are written using JSON Schema (a standard vocabulary β€” MongoDB supports draft 4 + some extensions)
  • Validation can be strict or moderate (more about this soon)
  • When a write violates the rules β†’ MongoDB rejects the operation and throws an error

2. Three Levels of Strictness (Very Important to Understand)

Validation Level What happens when document is invalid? When to use it Default when you enable validation
strict All fields must follow the schema (even fields not mentioned in schema are forbidden) Very controlled collections (financial, medical, config) No β€” you must set it explicitly
moderate Only fields mentioned in schema are validated. Extra fields are allowed Most real-world apps (best balance) Yes β€” this is the default
off No validation (default behavior of MongoDB) Prototyping / very flexible collections Yes (if you never set validator)

Teacher recommendation 2026: β†’ Start with moderate in almost all production cases β†’ Use strict only when you really want to forbid any undocumented field

3. Hands-on β€” Let’s Create & Test Schema Validation

Open mongosh and let’s do it step by step.

Step 1: Create collection with validation (recommended way)

JavaScript

Step 2: Test β€” Try correct insert

JavaScript

β†’ Success!

Step 3: Try invalid inserts β†’ watch MongoDB reject them

JavaScript

Step 4: Update also gets validated!

JavaScript

4. Quick Summary Table – Most Useful JSON Schema Keywords

Keyword Purpose Example Value
bsonType Enforce data type “string”, “double”, “objectId”, “date”, “array”
required Fields that must exist [“name”, “email”, “status”]
enum Only allow specific values [“active”, “inactive”, “pending”]
minimum / maximum Numeric range minimum: 0, maximum: 1000000
pattern Regex for strings “^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$” (email)
items Validate array elements { bsonType: “string” }
additionalProperties true/false/object schema for extra fields true (moderate), false (strict)

5. How to Add / Modify Validation on Existing Collection

JavaScript

6. Mini Exercise – Try Right Now!

  1. Create a products collection with validation:
    • required: name, price, category
    • price β‰₯ 0 and number
    • category in [“Electronics”, “Clothing”, “Books”]
    • sku matches pattern “^PROD-[A-Z0-9]{6}$”
  2. Try few valid & invalid inserts
  3. Try to update price to negative β†’ see rejection

Understood beta? Schema validation is not about making MongoDB “like SQL” β€” it’s about adding just enough safety rails so your data stays trustworthy without losing the flexibility that makes MongoDB great.

Next class β€” what shall we do?

  • Deep dive into more advanced JSON Schema (oneOf, allOf, dependencies)?
  • How to bypass validation temporarily (when importing legacy data)?
  • Schema validation + aggregation (validate existing data)?
  • Or back to building a small app with validation + CRUD + aggregation?

Tell me β€” class is yours! πŸš€β€οΈ

Any doubt about schema validation? Ask freely β€” we’ll test more rules together πŸ˜„

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *