MongoDB from Basics to Production · MongoDB in Production
Schema Validation with $jsonSchema
Enforce required fields, types, formats and allowed values at the database level with collection validators, and roll them out safely.
What you'll build
A users collection with a validator that requires an email with a plausible format, restricts role to known values and age to a range, and rejects invalid writes with a detailed explanation of what failed.
The idea
- MongoDB is schema-flexible, but production data usually has rules. A validator (
$jsonSchema) enforces them for every write path: application, scripts and imports. validationLevel(strictormoderate) andvalidationAction(errororwarn) control how strictly existing and new documents are checked;warnlogs violations without rejecting writes, useful while migrating.- Add validators to existing collections with
collMod.
The code
db.createCollection("users", {
validator: { $jsonSchema: {
bsonType: "object",
required: ["email", "role"],
properties: {
email: { bsonType: "string", pattern: "^[^@\\s]+@[^@\\s]+\\.[a-z]{2,}$" },
role: { enum: ["customer", "staff", "admin"] },
age: { bsonType: "int", minimum: 13, maximum: 130 },
},
} },
validationAction: "error",
});
db.users.insertOne({ email: "[email protected]", role: "customer", age: 31 });
print("valid document inserted");
for (const bad of [{ email: "not-an-email", role: "customer" }, { email: "[email protected]", role: "root" }, { email: "[email protected]" }]) {
try {
db.users.insertOne(bad);
} catch (e) {
const rule = e.errInfo.details.schemaRulesNotSatisfied[0];
const detail = rule.propertiesNotSatisfied?.[0]?.propertyName ?? rule.missingProperties;
print(e.message + ":", rule.operatorName, JSON.stringify(detail));
}
}
print("users:", db.users.countDocuments());
Output
valid document inserted Document failed validation: properties "email" Document failed validation: properties "role" Document failed validation: required ["role"] users: 1
Run this on your computer — see “Get Started” for setup.
Common mistakes
- Relying only on application validation; scripts and other services still write bad data.
- Turning on strict validation for a collection that already contains invalid documents, breaking updates to them; start with
validationAction: "warn"and clean up. - Overly strict schemas that block legitimate evolution; validate what must hold, not every optional field.
Key points
- $jsonSchema validators enforce rules for every writer.
- Error details explain exactly which rule failed.
- Roll out with warn, clean up, then enforce.
Further reading: Schema validation · $jsonSchema
Practice questions
Why add a database validator when the application already validates?
Answer
Other writers (scripts, imports, other services) bypass application code; the validator enforces rules for all of them.
What's the difference between validationAction error and warn?
Answer
error rejects invalid writes; warn allows them but logs the violation, which helps when introducing validation to existing data.
How do you add validation to an existing collection?
Answer
Run collMod with the validator, often starting with validationAction: 'warn' or validationLevel: 'moderate'.
Open in the app to mark lessons complete, take notes and track your progress.