Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 70 ยท Schema design

Schema Validation

Enforce document shape in MongoDB with a $jsonSchema validator, choose validationLevel and validationAction, change rules with collMod, and validate in code too.

MongoDB does not force documents to match a shape by default. That freedom is great while you are experimenting, and a liability once real traffic arrives: one buggy deploy can write price: "12 USD" instead of price: 12, and every report that adds prices up quietly breaks. Schema validation lets you attach rules to a collection so the database itself rejects (or flags) documents that do not fit.

This lesson shows the real mongosh syntax with a $jsonSchema validator, explains the two settings that control how strict it is, and then lets you run a small JSON-Schema-style checker that is written in plain JavaScript. As always, the shell blocks are real MongoDB and the TryIts are a stand-in (see The Practice Engine Used in This Tutorial).

What a validator can say

Types bsonType string, int, date, array, object.
Required Fields that must be present.
Ranges minimum, maximum, minLength, enum, pattern.
Nesting Rules for sub-objects and array items.
1 / 2

A validator in mongosh

You attach a validator when you create the collection. The $jsonSchema operator uses the JSON Schema vocabulary, with MongoDB's own bsonType for types:

JavaScript
db.createCollection("products", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "price"],
      properties: {
        name:  { bsonType: "string", minLength: 2 },
        price: { bsonType: ["int", "double", "decimal"], minimum: 0 },
        status: { enum: ["draft", "active", "retired"] },
        tags: { bsonType: "array", items: { bsonType: "string" } }
      }
    }
  },
  validationLevel: "strict",
  validationAction: "error"
})

With this in place, db.products.insertOne({ name: "Mug", price: -3 }) fails with a "Document failed validation" error (code 121), and nothing is written. bsonType accepts the type names you saw in BSON Types; the alias "number" matches any numeric type. Fields that are not listed in properties are allowed unless you add additionalProperties: false, which is rarely a good idea because it also forbids _id unless you list it.

You can also validate with ordinary query operators, for example validator: { price: { $gte: 0 } }, and combine them with $jsonSchema using $and. A $jsonSchema rule is usually easier to read and to generate error messages from.

The two dials

validationLevel decides which writes are checked:

  • strict (the default): every insert and every update is validated.
  • moderate: inserts are validated, and updates are validated only if the existing document already passes. Documents that were invalid before you added the rule can still be edited, so you can introduce validation to an existing collection without freezing the bad data in place.
  • off: nothing is checked.

validationAction decides what happens to an invalid write:

  • error (the default): the write is rejected.
  • warn: the write goes through, and the problem is written to the server log. This is a good first step: turn on warn, read the log for a few days, fix the producers, then switch to error.

You change both on an existing collection with the collMod command:

JavaScript
db.runCommand({
  collMod: "products",
  validator: { $jsonSchema: { bsonType: "object", required: ["name", "price", "sku"] } },
  validationLevel: "moderate",
  validationAction: "warn"
})

db.getCollectionInfos({ name: "products" })[0].options   // inspect the current rules

Changing a validator does not check documents that are already stored. To find the ones that would fail, query for them with the negated schema: db.products.find({ $nor: [{ $jsonSchema: schema }] }). Putting a schema in a variable first keeps the two uses identical.

Trying the idea in the browser

Below is a stand-in: a small function that checks a document against a schema object using the same keywords (bsonType, required, properties, minimum, maximum, minLength, enum, pattern, items). It does not cover all of JSON Schema, and real MongoDB reports validation failures differently, but the pass/fail logic is the same idea. JavaScript numbers do not distinguish int from double, so the stand-in treats a whole number as int and double is anything else.

JS A JSON-Schema-style checker

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that one bad document can break several rules at once, and that the checker never complains about a field it does not know about, exactly like a validator without additionalProperties.

Level and action in practice

The second stand-in wraps the checker in a tiny collection that has a validationLevel and validationAction. It starts with one document that was stored before a rule existed, which is the situation moderate is designed for.

JS strict versus moderate, error versus warn

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare the three runs. strict blocks the harmless edit to the old document because the result is still invalid. moderate lets it through, but still protects the valid document and new inserts. warn lets everything pass and only reports.

Validate in the application too

Database validation is a safety net, not a replacement for checking input where it enters your program:

  • Better messages. The server's message says "Document failed validation"; your app can tell the user which field to fix. (Newer servers include details about which rule failed, but they are meant for developers, not end users.)
  • Fewer round trips. Rejecting a bad request before it reaches the database saves work.
  • Rules the database cannot express, such as "this coupon exists" or "the end date is after the start date in another document".
  • Several apps, one database. The validator is the one place every writer has to pass through, which is why you still want it.

The practical pattern is to validate with your language's tools (an ODM schema such as Mongoose, or your own checks), and keep a looser $jsonSchema in the database that guards the essentials: required fields, key types and enums. Version both together, and keep the database rule slightly simpler so that application changes do not require a collMod every time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does validationLevel: "moderate" do?

    Moderate checks inserts, and checks an update only if the existing document was valid before. That lets you add rules to a collection that already contains non-conforming data.
  2. 2. You add a validator to a collection that holds 1 million documents. What happens to the existing documents?

    A validator applies to writes. To find stored documents that would fail, query with $nor and the same $jsonSchema.
  3. 3. Which setting lets bad writes through but records them in the server log?

    validationAction decides what happens on failure. warn allows the write and logs it, which makes it a good rollout step before switching to error.
  4. 4. Why validate in the application as well as in the database?

    The validator is a safety net every writer must pass, but your application can report friendly errors, avoid wasted round trips and check rules that span several documents.

Summary

  • A $jsonSchema validator on a collection rejects or flags documents that break its rules: bsonType, required, properties, enum, ranges, patterns and array items.
  • validationLevel (strict, moderate, off) chooses which writes are checked; validationAction (error, warn) chooses what happens on failure.
  • Change rules on a live collection with collMod; existing documents are not re-checked, so find them with $nor and the same schema.
  • Roll out in steps: warn, fix writers, then error; use moderate when old data does not conform.
  • Validate in the application too, for better messages and rules the database cannot express.
  • The TryIts are a JavaScript stand-in for the idea, not the real server validator.

Next, put design decisions together in Case Study: Modeling an Online Shop.