Validation basics
Schema validation lets you require fields and types even though MongoDB is flexible.
In this page:
Syntax
db.createCollection("collection_name", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["field1"],
properties: { field1: { bsonType: "string" } }
}
}
})
Validation basics
When creating a collection, add a validator using $jsonSchema to demand required fields, types and value ranges. validationAction chooses whether invalid writes are rejected (error) or only logged (warn).
Existing documents are not re-checked until they are updated.
Note:
Start with validationAction warn to see what would fail before enforcing.
Example: Validation basics
test> db.createCollection("accounts", {
... validator: { $jsonSchema: {
... bsonType: "object",
... required: ["email", "age"],
... properties: {
... email: { bsonType: "string" },
... age: { bsonType: "int", minimum: 18 }
... }
... } }
... })
{ ok: 1 }
test> db.accounts.insertOne({ email: "[email protected]", age: 15 })
MongoServerError: Document failed validation
test> db.accounts.insertOne({ email: "[email protected]", age: 30 })
{ acknowledged: true, insertedId: ObjectId('65a1b2c3d4e5f60718293a4e') }
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Assuming MongoDB always enforces a schema
- Forgetting validation only applies on writes
- Making validators too strict for real data
Chapter Summary
- $jsonSchema defines required fields and types
- validationAction is error or warn
- Set at collection creation or with collMod
- Checked on inserts and updates
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: