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
validationLeveltostrictormoderate, which controls when validation applies. - Using incorrect BSON types like
stringinstead ofbsonType: "string". - Forgetting to include required fields in the
requiredarray. - 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
| Option | Description |
|---|---|
| validator | Defines the JSON Schema validation rules for the collection |
| $jsonSchema | Specifies the schema details like required fields and data types |
| bsonType | Specifies the BSON data type (e.g., string, int, object) for a field |
| required | Array of field names that must be present in documents |
| validationLevel | Controls when validation applies: strict (default), moderate, or off |
| validationAction | Action 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.