0
0
MongodbHow-ToBeginner · 4 min read

How to Validate Schema in MongoDB: Syntax and Examples

In MongoDB, you validate schema by defining validator rules using JSON Schema in the createCollection or collMod commands. These rules enforce document structure and data types automatically when inserting or updating documents.
📐

Syntax

MongoDB uses the validator option with JSON Schema to enforce schema rules on collections. You specify this when creating a collection or modifying an existing one.

  • createCollection: Creates a new collection with validation rules.
  • collMod: Modifies an existing collection to add or change validation.
  • $jsonSchema: Defines the schema rules like required fields and data types.
mongodb
db.createCollection("myCollection", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "age"],
      properties: {
        name: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        age: {
          bsonType: "int",
          minimum: 0,
          description: "must be an integer >= 0 and is required"
        }
      }
    }
  }
})
💻

Example

This example creates a collection named users with schema validation that requires username as a string and email as a string matching an email pattern.

mongodb
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["username", "email"],
      properties: {
        username: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        email: {
          bsonType: "string",
          pattern: "^.+@.+\\..+$",
          description: "must be a valid email and is required"
        }
      }
    }
  },
  validationLevel: "strict"
})

// Insert valid document
db.users.insertOne({ username: "alice", email: "alice@example.com" })

// Insert invalid document (missing email)
try {
  db.users.insertOne({ username: "bob" })
} catch(e) {
  print(e.message)
}
Output
WriteError({"index":0,"code":121,"errmsg":"Document failed validation","op":{"username":"bob"}})
⚠️

Common Pitfalls

Common mistakes when validating schema in MongoDB include:

  • Not setting validationLevel to strict or moderate, which controls when validation applies.
  • Using incorrect BSON types like string instead of bsonType: "string".
  • Forgetting to include required fields in the required array.
  • Not testing inserts or updates to confirm validation works.
mongodb
/* Wrong: missing bsonType keyword */
db.createCollection("wrongCollection", {
  validator: {
    $jsonSchema: {
      required: ["name"],
      properties: {
        name: {
          type: "string"  // Incorrect, should be bsonType
        }
      }
    }
  }
})

/* Correct: use bsonType */
db.createCollection("rightCollection", {
  validator: {
    $jsonSchema: {
      required: ["name"],
      properties: {
        name: {
          bsonType: "string"
        }
      }
    }
  }
})
📊

Quick Reference

OptionDescription
validatorDefines the JSON Schema validation rules for the collection
$jsonSchemaSpecifies the schema details like required fields and data types
bsonTypeSpecifies the BSON data type (e.g., string, int, object) for a field
requiredArray of field names that must be present in documents
validationLevelControls when validation applies: strict (default), moderate, or off
validationActionAction on validation failure: error (default) or warn

Key Takeaways

Use the validator option with $jsonSchema to enforce schema rules in MongoDB collections.
Always specify bsonType for fields and list required fields in the required array.
Set validationLevel to strict to ensure all inserts and updates are checked.
Test your schema validation by inserting valid and invalid documents.
Common errors include using incorrect type keywords and missing required fields.