Fix MongoDB 'MongoServerError: Document failed validation' when inserting or updating data

intermediate๐Ÿƒ MongoDB2026-03-28| MongoDB Server v3.6+ (any OS), applications using MongoDB drivers (e.g., Node.js, Python, Java, C#) or the `mongosh` shell.

Error Message

MongoServerError: Document failed validation
#mongodb#validation#schema#json-schema#insert#update

TL;DR Quick Fix

The MongoServerError: Document failed validation error means the data you're trying to insert or update doesn't meet the schema validation rules defined for your MongoDB collection. The quickest way to fix this is to:

  • Inspect the document you're trying to insert/update.
  • Check the collection's validation rules using db.getCollectionInfos({ name: 'yourCollectionName' }).
  • Adjust your data to comply with the rules, or (if appropriate) modify the collection's validation rules.

Detailed Root Cause

MongoDB introduced schema validation starting with version 3.6. This feature allows you to enforce structural and data type constraints on documents within a collection. When you attempt an insert or update operation, MongoDB checks the incoming document against these predefined rules.

If the document fails to satisfy any part of the validation rule (e.g., a required field is missing, a field has the wrong data type, a value is outside an allowed range, or an extra field is present when not allowed), MongoDB rejects the operation and throws a MongoServerError: Document failed validation.

This error is a good thing! It means your database is actively protecting data integrity according to the rules you (or another developer) set up. Your task is to understand why the document is considered invalid and bring it into compliance.

Fix Approaches

Approach 1: Examine the Data Being Inserted or Updated

The first step is always to look at the exact document that triggered the error. Often, the problem lies in a simple typo, a missing field, or an incorrect data type in your application's data payload.

Example of problematic data:

Let's say your collection expects a name (string), age (integer), and email (string, required). You try to insert:


{
  "username": "johndoe",
  "age": "twenty-five",
  "email": "john.doe@example.com"
}

Here, username might not be expected, age is a string instead of an integer, and the required name field is missing. Any of these could cause validation to fail.

Go back to your application code and inspect the object or dictionary you're passing to the MongoDB driver's insertOne, insertMany, updateOne, or updateMany methods. Print it to your console or debugger to see its exact structure and values.

Approach 2: Review the Collection's Schema Validation Rules

Once you know what data you're sending, you need to know what rules it's being compared against. You can retrieve a collection's validation rules using the db.getCollectionInfos() command in mongosh:


db.getCollectionInfos({ name: 'yourCollectionName' });

This will return an array of information about your collection. Look for the options.validator field. Here's an example of what you might see:


[
  {
    "name": "yourCollectionName",
    "type": "collection",
    "options": {
      "validator": {
        "$jsonSchema": {
          "bsonType": "object",
          "required": ["name", "email", "age"],
          "properties": {
            "name": {
              "bsonType": "string",
              "description": "Must be a string and is required"
            },
            "email": {
              "bsonType": "string",
              "pattern": "^.+@.+\\..+$",
              "description": "Must be a valid email address and is required"
            },
            "age": {
              "bsonType": "int",
              "minimum": 18,
              "description": "Must be an integer >= 18 and is required"
            },
            "status": {
              "enum": ["active", "inactive", "pending"],
              "description": "Can only be one of the enum values"
            }
          },
          "additionalProperties": false
        }
      },
      "validationAction": "error",
      "validationLevel": "strict"
    }
  }
]

In this example:

  • required: ["name", "email", "age"]: These fields must be present.
  • bsonType: "string" for name and email, bsonType: "int" for age: Data types are enforced.
  • minimum: 18 for age: The value must be at least 18.
  • pattern: "^.+@.+\\..+$" for email: A regular expression for email format.
  • enum: ["active", "inactive", "pending"] for status: The value must be one of these.
  • additionalProperties: false: This is crucial! It means no fields other than those explicitly listed in properties are allowed.

Compare your document (from Approach 1) against these rules. You'll likely spot the discrepancy immediately.

Approach 3: Adjust Data to Match Schema

Once you've identified the mismatch, modify your application's data before sending it to MongoDB. This is usually the preferred solution, as it maintains data integrity.

Using our problematic data and the schema from Approach 2, here's how to correct it:


{
  "name": "John Doe",        // Added 'name' field
  "age": 25,                 // Changed 'age' to integer, not string
  "email": "john.doe@example.com" // Email is correct
  // Removed 'username' because 'additionalProperties: false' in schema
}

Now, if you try to insert this corrected document, it should pass validation:


db.yourCollectionName.insertOne({
  "name": "John Doe",
  "age": 25,
  "email": "john.doe@example.com"
});

Approach 4: Modify the Schema Validation Rules (If Necessary)

Sometimes, the validation rules themselves might be incorrect, too strict, or outdated for your current application logic. In such cases, you might need to modify the collection's validator. This should be done carefully, as it affects all future operations on the collection.

You can use the collMod command to change validation rules:


db.runCommand({
  collMod: 'yourCollectionName',
  validator: {
    // Your new or modified validation rules here
    // For example, to allow a 'username' field:
    "$jsonSchema": {
      "bsonType": "object",
      "required": ["name", "email", "age"],
      "properties": {
        "name": { "bsonType": "string" },
        "email": { "bsonType": "string", "pattern": "^.+@.+\\..+$" },
        "age": { "bsonType": "int", "minimum": 18 },
        "username": { "bsonType": "string", "minLength": 3 } // New field allowed
      },
      "additionalProperties": false // Still no other arbitrary fields
    }
  },
  validationAction: 'error', // 'error' (default) or 'warn'
  validationLevel: 'strict'  // 'strict' (default) or 'moderate'
});

  • validationAction: Determines what happens on a validation failure. 'error' rejects the operation, 'warn' logs a warning but allows the operation.
  • validationLevel: Determines which operations are subject to validation. 'strict' applies to all inserts and updates. 'moderate' applies to inserts and updates on existing valid documents (updates on existing invalid documents are not validated).

To completely disable validation for a collection, you can set the validator to an empty object:


db.runCommand({
  collMod: 'yourCollectionName',
  validator: {},
  validationAction: 'warn'
});

This is generally not recommended for production environments unless you have strong application-level validation.

Approach 5: Handle Validation Errors in Application Code

In robust applications, you should anticipate validation errors and handle them gracefully. Most MongoDB drivers will throw an exception or return an error object that you can catch.

Example (Node.js/JavaScript pseudo-code):


const { MongoClient } = require('mongodb');

async function insertUser(userData) {
  const client = new MongoClient('mongodb://localhost:27017');
  try {
    await client.connect();
    const database = client.db('mydb');
    const users = database.collection('users');

    const result = await users.insertOne(userData);
    console.log(`Successfully inserted user with _id: ${result.insertedId}`);
  } catch (error) {
    if (error.name === 'MongoServerError' && error.code === 121) { // 121 is the error code for DocumentValidationFailure
      console.error('Document failed validation:', error.message);
      console.error('Problematic document:', JSON.stringify(userData, null, 2));
      // Log the specific validation errors if available in error details
      // (MongoDB error messages can sometimes include details on which rule failed)
    } else {
      console.error('An unexpected error occurred:', error);
    }
  } finally {
    await client.close();
  }
}

// Example usage with invalid data:
insertUser({
  username: 'testuser',
  age: 'twenty',
  email: 'invalid'
});

By catching the specific MongoServerError and inspecting its details (especially error.message or potentially error.errInfo.details), you can provide better feedback to the user or log more specific diagnostic information.

Prevention

  • Application-Level Validation: Implement robust validation in your application layer before sending data to MongoDB. This provides immediate feedback to users and reduces unnecessary database calls. Libraries like Joi, Yup (for Node.js), Pydantic (for Python), or Hibernate Validator (for Java) are excellent for this.

  • Clear Schema Documentation: Document your MongoDB collection schemas and validation rules clearly for all developers working on the project.

  • Automated Testing: Write unit and integration tests that specifically test your data models against your MongoDB schema validation rules.

  • Use a JSON Validator Tool: When I'm debugging complex JSON structures or trying to ensure my data conforms to a specific format, I often use a tool like ToolCraft's JSON Formatter & Validator. It's a quick, browser-based way to check for syntax errors or just get a clean view of your JSON before you even send it to the database. Super handy for catching simple mistakes that could lead to validation errors, especially with intricate $jsonSchema rules.

Verification Steps

After applying a fix (either by correcting your data or modifying the schema rules):

  • Re-attempt the operation: Try to insert or update the data again. If the error no longer appears, that's a good sign.

  • Query the collection: Use db.yourCollectionName.find({ _id: yourDocumentId }) or a relevant query to ensure the document was successfully inserted or updated and appears as expected in the database.

  • Test edge cases: If you modified the schema, try inserting data that should now pass (but previously failed) and data that should still fail to ensure your new validation rules are behaving as intended.

Further Reading

Related Error Notes