Skip to content

Lesson 3 of 9 · 24m

Schema Validation and Evolution in a Schemaless System

Use JSON Schema validators, disciplined migrations, and versioned shapes so flexible documents do not become untyped production folklore.

MongoDB is often sold as schemaless, which experienced engineers translate as "the schema moved into every service, cron job, and dashboard query." Flexible documents are valuable because they can evolve. They are dangerous because they can evolve inconsistently. Your job is not to eliminate schema; it is to put schema where it can be enforced, tested, and migrated.

Use collection validators for invariants

MongoDB supports JSON Schema validation at the collection level:

db.createCollection("orders", {
  validator: {
    $jsonSchema: {
      bsonType: "object", required: ["customerId", "status", "items", "createdAt"],
      properties: {
        customerId: { bsonType: "objectId" },
        status: { enum: ["cart", "paid", "packed", "shipped", "cancelled"] },
        items: {
          bsonType: "array", minItems: 1,
          items: {
            bsonType: "object", required: ["sku", "quantity", "unitPrice"],
            properties: {
              sku: { bsonType: "string" },
              quantity: { bsonType: "int", minimum: 1 },
              unitPrice: { bsonType: "int", minimum: 0 }
            }
          }
        }, createdAt: { bsonType: "date" }
      }
    }
  },
  validationLevel: "strict", validationAction: "error"
})

This does not replace application validation, but it prevents bad writes from scripts, migration jobs, and the one service nobody remembered was still connected.

Version document shapes explicitly

When shape evolution is unavoidable, include a version field:

{ schemaVersion: 3, customerId: ObjectId(), status: "paid" }

Readers can branch deliberately, migrations can measure progress, and observability can report how many old shapes remain. A version field is ugly only until the first incident caused by silently mixed representations.

Migrate in small observable batches

A migration script should be boring and resumable:

db.orders.find({ schemaVersion: { $lt: 3 } }).limit(500).forEach(doc => {
    db.orders.updateOne(
      { _id: doc._id, schemaVersion: doc.schemaVersion },
      {
        $set: {
          schemaVersion: 3,
          totals: { subtotal: doc.subtotal ?? 0, currency: doc.currency ?? "USD" }
        }
      }
    )
  })

Use predicates in both reads and updates so retries are safe. Batch, measure lag, and stop when object storage, replication lag, or application latency says stop. Big-bang migrations in production are usually a failover exercise you did not mean to schedule.

Beware partial schema enforcement

If validation applies only to new writes, old invalid documents remain. If it applies to all writes, unrelated updates to legacy records can suddenly fail. validationLevel: "moderate" can exempt documents that already fail validation, but understand that this is a transitional compromise, not a steady state.

Schema is also a contract with analytics

Application code is not the only consumer. BI exports, change streams, search indexing, and machine-learning jobs all depend on stable field meanings. Renaming a field without a downstream inventory is a breaking API change even if no HTTP API changed.

Field notes

  • Put required invariant checks in the database and contextual validation in application code.
  • Never assume a field type; mixed int, long, and decimal values make sorting and comparisons surprising.
  • Test migration scripts against production-shaped data, especially missing and malformed legacy fields.
  • Flexibility is useful when governed. Ungoverned flexibility is just delayed coupling.

Was this lesson helpful?

Sign in to rate