How to fix MongoServerError: Document failed validation in MongoDB
This error occurs when trying to insert or update a document that violates the collection's validation rules. MongoDB rejects the operation to maintain data integrity based on the schema constraints you've defined.
Quick fix
Fixes 121
try {
await collection.insertOne({ name: "John", age: "25" }); // age should be number
} catch (error) {
console.log('Error code:', error.code); // 121
console.log('Error info:', JSON.stringify(error.errInfo, null, 2));
// Shows which field and why it failed
}- Examine the validation error details
- Review the collection validator definition
- Fix the document to match the schema
- Update the validator if rules are too strict
try {await collection.insertOne({ name: "John", age: "25" }); // age should be number} catch (error) {console.log('Error code:', error.code); // 121console.log('Error info:', JSON.stringify(error.errInfo, null, 2));// Shows which field and why it failed}MongoServerError: Document failed validation
What this error means
MongoDB schema validation allows you to enforce data quality rules at the database level. When you define a validator for a collection (using JSON Schema or other query operators), MongoDB checks every insert and update operation against these rules. The "Document failed validation" error means that the document you're trying to write doesn't meet the validation criteria. This could be due to missing required fields, incorrect data types, values outside allowed ranges, or any other constraint violation defined in your schema. By default, MongoDB uses the "error" validation action, which rejects invalid documents completely. Starting in MongoDB 5.0, the error includes an "errInfo" field with detailed information about which specific validation rule was violated, making debugging much easier.
Typical symptoms
- Insert or update operations fail with error code 121
- Error message shows "Document failed validation" without specific details (pre-5.0)
- Detailed validation failure reasons appear in errInfo field (MongoDB 5.0+)
- Operations succeed in development but fail in production with validation rules
- Bulk write operations partially succeed, with some documents rejected
Common causes
- Document missing required fields defined in the schema validator
- Field values have incorrect data types (e.g., string instead of number)
- Values fall outside allowed ranges or enum options
- Nested document structures don't match the expected schema shape
- Array fields violate length constraints or contain invalid items
- Custom validation expressions evaluate to false for the document
- Updates modify fields in ways that violate validation rules
How to fix "MongoServerError: Document failed validation"
Check the complete error object to understand what failed. In MongoDB 5.0+, the errInfo field contains specific details:
try {
await collection.insertOne({ name: "John", age: "25" }); // age should be number
} catch (error) {
console.log('Error code:', error.code); // 121
console.log('Error info:', JSON.stringify(error.errInfo, null, 2));
// Shows which field and why it failed
}For earlier versions, you may need to inspect your validator definition manually to identify the issue.
Check what validation rules are currently enforced on your collection:
const db = client.db('myDatabase');
const collections = await db.listCollections({ name: 'myCollection' }).toArray();
const validator = collections[0]?.options?.validator;
console.log('Current validator:', JSON.stringify(validator, null, 2));Or using the MongoDB shell:
db.getCollectionInfos({ name: "myCollection" })[0].options.validatorThis shows the exact JSON Schema or query expression that documents must satisfy.
Modify your document to satisfy all validation rules. Common fixes:
Missing required fields:
// ❌ Fails validation
await collection.insertOne({ name: "John" });
// ✅ Includes required email field
await collection.insertOne({
name: "John",
email: "john@example.com"
});Wrong data types:
// ❌ Age as string
await collection.insertOne({ name: "John", age: "25" });
// ✅ Age as number
await collection.insertOne({ name: "John", age: 25 });Value constraints:
// ❌ Age outside allowed range
await collection.insertOne({ name: "John", age: 150 });
// ✅ Age within valid range
await collection.insertOne({ name: "John", age: 25 });If the validation rules don't match your actual requirements, you can modify them:
await db.command({
collMod: 'myCollection',
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['name', 'email'],
properties: {
name: {
bsonType: 'string',
description: 'must be a string and is required'
},
email: {
bsonType: 'string',
pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
description: 'must be a valid email and is required'
},
age: {
bsonType: 'int',
minimum: 0,
maximum: 120,
description: 'must be an integer between 0 and 120'
}
}
}
},
validationLevel: 'strict',
validationAction: 'error'
});Be careful when loosening validation rules in production - this affects data quality.
If you need to update existing documents that don't meet new validation rules, use moderate validation:
await db.command({
collMod: 'myCollection',
validationLevel: 'moderate' // Only validates new inserts and updates to valid docs
});With validationLevel: 'moderate', MongoDB:
- Applies validation to all new inserts
- Applies validation to updates on documents that currently pass validation
- Skips validation for updates to documents that already fail validation
This allows you to gradually migrate legacy data while enforcing rules for new data.
Switch back to 'strict' once all documents are compliant.
Advanced notes
Validation Actions
Beyond rejecting documents, MongoDB offers a "warn" validation action that logs violations without blocking writes:
await db.command({
collMod: 'myCollection',
validationAction: 'warn' // Logs violations, allows writes
});This is useful for monitoring data quality issues in development or when migrating to stricter validation rules.
Validation Performance
Schema validation adds overhead to write operations. For high-throughput applications:
- Keep validators simple and avoid complex nested conditions
- Use indexes on validated fields to speed up constraint checks
- Consider application-level validation for complex business logic
- Monitor validation latency in production
Bypass Validation (Use with Caution)
In rare cases, you may need to bypass validation temporarily:
await collection.insertOne(
{ invalidDoc: true },
{ bypassDocumentValidation: true }
);This requires appropriate privileges and should only be used for emergency fixes or data migrations.
Validation with Mongoose
If using Mongoose, schema validation happens at the application level before MongoDB's native validation. You may encounter Mongoose validation errors before reaching MongoDB's validator. Check both layers when troubleshooting.
Frequently asked questions
- What does "121" mean?
- MongoDB schema validation allows you to enforce data quality rules at the database level. When you define a validator for a collection (using JSON Schema or other query operators), MongoDB checks every insert and update operation against these rules. The "Document failed validation" error means that the document you're trying to write doesn't meet the validation criteria.
- How do I fix "121"?
- This error occurs when trying to insert or update a document that violates the collection's validation rules. MongoDB rejects the operation to maintain data integrity based on the schema constraints you've defined.
- What causes "121"?
- Document missing required fields defined in the schema validator Field values have incorrect data types (e.g., string instead of number) Values fall outside allowed ranges or enum options
- Is the "121" error serious?
- It is a medium-severity error — more of a blocker than a risk. The steps above resolve it.
Official resources & further reading
- 📚MongoDB Official Documentation
- 📖mongodb.com - schema validation(Official Docs)
- 📖mongodb.com - handle invalid documents(Official Docs)
- 📖mongodb.com - mongodb 5 0 schema validation(Official Docs)
- 📖mongodb.com - specify validation level(Official Docs)
- 📖mongodb.com - 118117(Official Docs)