Why Schema Validation Matters
MongoDB is schemaless, which means you can store any document structure in a collection. That's powerful, but it can also be dangerous. Without validation, you might end up with inconsistent data that breaks your application.
Schema validation is like having a bouncer at the door of your collection. It checks every document before it gets in, making sure it matches your rules. No malformed data gets through.
Even though MongoDB is flexible, most applications benefit from some level of structure. Schema validation gives you the best of both worlds: flexibility when you need it, structure when you want it.
Creating Validation Rules
You add validation rules when creating or modifying a collection. The rules use JSON Schema syntax, which describes what your documents should look like.
You can validate field types, required fields, value ranges, and even patterns. It's like setting up a form with required fields and input validation.
Validation rules are checked on every insert and update. If a document doesn't match, MongoDB rejects it with an error.
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "age"],
properties: {
name: {
bsonType: "string",
description: "Must be a string and is required"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "Must match email format"
},
age: {
bsonType: "int",
minimum: 0,
maximum: 150,
description: "Must be between 0 and 150"
}
}
}
}
})
Validation Levels
MongoDB offers different validation levels to control how strictly rules are enforced. Think of them as different levels of security at an airport.
The strict level checks all inserts and updates. The moderate level only checks updates to existing documents that already pass validation. The off level disables validation entirely.
Moderate validation is useful when you have legacy data that doesn't match new rules. You can fix it gradually as you update those documents.
db.runCommand({
collMod: "users",
validationLevel: "moderate",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: { bsonType: "string" },
email: { bsonType: "string" }
}
}
}
})
Validation Actions
When a document fails validation, MongoDB needs to know what to do. You can set the validation action to either error or warn.
error rejects the operation entirely. warn logs a warning but allows the operation to proceed. Warning mode is great for testing new validation rules without breaking your application.
You can combine different validation levels and actions to create a gradual rollout strategy. Start with warn mode, monitor the logs, then switch to error mode when you're confident.
db.runCommand({
collMod: "products",
validationAction: "warn",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price"],
properties: {
name: { bsonType: "string" },
price: {
bsonType: "double",
minimum: 0,
description: "Price must be positive"
}
}
}
}
})