MongoDB is famously flexible and schemaless. However, total flexibility can cause messy data. Schema validation enforces rules at the database level.
In production, data integrity is vital. You do not want documents missing required fields. Validation guarantees consistency across your app.
MongoDB uses standard JSON Schema rules. You define the exact shape a document must take. It verifies types, requirements, and value ranges.
Rules are applied during collection creation. You pass a validator object to createCollection(). Existing collections can also be modified using collMod.
You can specify fields that must always exist. If an insert lacks the field, it is rejected instantly. This behaves like a SQL NOT NULL constraint.
// Create a collection with strict validation
db.createCollection("contacts", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
email: {
bsonType: "string",
pattern: "^.+@.+$",
description: "must be a valid email string"
}
}
}
}
});
You can control what happens when rules break. The error action blocks the insert completely. The warn action allows the insert but logs a warning.
The strict level checks all inserts and updates. The moderate level only checks documents that already comply. Moderate is great when adding rules to older databases.
Schema Validation protects your application data. It bridges the gap between NoSQL flexibility and SQL strictness. Use JSON Schema rules to require fields and types.
Which validation action completely blocks an invalid document from being saved?