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.
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.
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: "[email protected]"
});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.
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.
StaleShardVersion: shard version mismatch
How to fix "StaleShardVersion: shard version mismatch" in MongoDB
MongoOperationTimeoutError: Operation timed out
How to fix "MongoOperationTimeoutError: Operation timed out" in MongoDB
MongoServerError: PlanExecutor error during aggregation :: caused by :: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation.
How to fix "QueryExceededMemoryLimitNoDiskUseAllowed" in MongoDB
MissingSchemaError: Schema hasn't been registered for model
How to fix "MissingSchemaError: Schema hasn't been registered for model" in MongoDB/Mongoose
CastError: Cast to ObjectId failed for value "abc123" at path "_id"
How to fix "CastError: Cast to ObjectId failed" in MongoDB