Document failed to pass schema validation
This error occurs when an insert or update operation attempts to write a document that violates the schema validation rules defined for the collection. The database rejects the write to enforce data consistency.
- 1Inserting a document that is missing a required field
- 2Updating a field with a value of the wrong data type (e.g., a string where a number is required)
- 3A value in a field does not conform to a specified regex pattern in the validator
- 4An update causes a document to fall outside the rules defined in the `$jsonSchema` validator
An `insertOne` operation attempts to insert a document missing a required `email` field.
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: { bsonType: "string" },
email: { bsonType: "string" }
}
}
}
});
// This insert fails because the 'email' field is missing.
db.users.insertOne({ name: "Alice" });expected output
MongoServerError: Document failed validation
Fix 1
Correct the Document Data
WHEN The data being sent is incorrect or incomplete.
// Correct: Provide all required fields with the correct data types.
db.users.insertOne({
name: "Alice",
email: "alice@example.com"
});Why this works
The most direct fix is to ensure the document being written conforms to the collection's validation rules. Check the error message for details on which rule was violated.
Fix 2
Update the Validation Schema
WHEN The validation rules are too strict or no longer correct.
// Use collMod to update the validator, e.g., to make 'email' not required.
db.runCommand({
collMod: "users",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name"], // 'email' is no longer required
properties: {
name: { bsonType: "string" },
email: { bsonType: "string" }
}
}
}
})Why this works
If the data is valid but the rules are wrong, an administrator can modify the collection's validation schema using the `collMod` command.
Fix 3
Bypass Validation for a Specific Operation
WHEN You need to insert or update a document that you know is an exception (use with caution).
// This option allows the write to succeed even if it fails validation.
db.users.updateOne(
{ name: "Alice" },
{ $set: { email: 123 } }, // Invalid type
{ bypassDocumentValidation: true }
);Why this works
The `bypassDocumentValidation` option can be used on a per-operation basis to skip validation. This requires a user role that grants the `bypassDocumentValidation` privilege and should be used sparingly.
✕ Set the validation level to 'off' or 'warn' just to suppress the error
This defeats the purpose of schema validation and allows inconsistent or invalid data into your database, leading to application-level bugs.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev