Schema Validation

MongoDB Schema Validation

MongoDB is famously flexible and schemaless. However, total flexibility can cause messy data. Schema validation enforces rules at the database level.

Why Validate?

In production, data integrity is vital. You do not want documents missing required fields. Validation guarantees consistency across your app.

JSON Schema Standards

MongoDB uses standard JSON Schema rules. You define the exact shape a document must take. It verifies types, requirements, and value ranges.

Adding Validation Rules

Rules are applied during collection creation. You pass a validator object to createCollection(). Existing collections can also be modified using collMod.

Required Fields

You can specify fields that must always exist. If an insert lacks the field, it is rejected instantly. This behaves like a SQL NOT NULL constraint.

Validation Example:

// Create a collection with strict validation
db.createCollection("contacts", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name: {
          bsonType: "string",
          description: "must be a string and is required"
        },
        email: {
          bsonType: "string",
          pattern: "^.+@.+$",
          description: "must be a valid email string"
        }
      }
    }
  }
});

Validation Actions

You can control what happens when rules break. The error action blocks the insert completely. The warn action allows the insert but logs a warning.

Validation Levels

The strict level checks all inserts and updates. The moderate level only checks documents that already comply. Moderate is great when adding rules to older databases.

Summary

Schema Validation protects your application data. It bridges the gap between NoSQL flexibility and SQL strictness. Use JSON Schema rules to require fields and types.

Exercise

Which validation action completely blocks an invalid document from being saved?