Error
Error Code: 121

MongoDB Error 121: Document Validation Failed

📦 MongoDB
📋

Description

Error 121 signifies that a document failed to pass the validation rules defined for its target collection. This typically occurs during insert, update, or replace operations when the document's structure, data types, or values do not meet the specified schema constraints.
💬

Error Message

Document Validation Failure
🔍

Known Causes

4 known causes
⚠️
Document Structure Mismatch
The document being inserted or updated contains fields, types, or nesting that violate the collection's defined JSON Schema or validation rules.
⚠️
Missing Required Fields
A document is missing one or more fields that are explicitly marked as required by the collection's validation rules.
⚠️
Incorrect Data Types
A field in the document contains a value with a data type that does not match the expected type defined in the collection's validation schema.
⚠️
Invalid Field Values
A field's value fails to meet specified constraints, such as being outside a numerical range, not matching a regular expression pattern, or failing an enum check.
🛠️

Solutions

5 solutions available

1. Fix Document to Match Schema easy

Update document to pass validation

1
Check validation rules
db.getCollectionInfos({ name: "users" })[0].options.validator
2
Fix document to match schema
// If schema requires email:
db.users.insertOne({
  name: "John",
  email: "john@example.com"  // Required field
});

2. Update Validation Rules medium

Modify schema if rules are too strict

1
Update validator
db.runCommand({
  collMod: "users",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name"],  // Only name required now
      properties: {
        name: { bsonType: "string" },
        email: { bsonType: "string" }  // Optional
      }
    }
  }
});

3. Change Validation Level medium

Use moderate validation for existing docs

1
Set validation level
db.runCommand({
  collMod: "users",
  validationLevel: "moderate"  // Only validate inserts and valid-to-valid updates
});

// Options:
// "strict" - All inserts and updates
// "moderate" - Inserts and updates to valid docs
// "off" - No validation

4. Use validationAction: warn easy

Log warning instead of rejecting

1
Change to warning mode
db.runCommand({
  collMod: "users",
  validationAction: "warn"  // Log but allow
});

5. Bypass Validation Temporarily advanced

For data migration only

1
Use bypassDocumentValidation
db.users.insertOne(
  { name: "John" },  // Missing required field
  { bypassDocumentValidation: true }
);
🔗

Related Errors

5 related errors