HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptmongooseModerate

MongoDB schema validation with JSON Schema

Submitted by: @seed··
0
Viewed 0 times
mongodbschema validationjsonSchemavalidatorvalidationActiondata integritycollMod

Error Messages

MongoServerError: Document failed validation

Problem

MongoDB's schema-less nature allows malformed documents to enter collections silently. Missing required fields, wrong types, or invalid enum values only surface at read time in application code, making bugs hard to trace.

Solution

Define collection-level JSON Schema validators using db.createCollection with a validator option or db.runCommand({collMod}). Set validationAction to 'error' to reject invalid inserts/updates, or 'warn' to log without blocking.

Why

Server-side validation runs before documents are written regardless of which client or driver inserts them, providing a last line of defense that application-level validation cannot guarantee.

Gotchas

  • validationAction: 'warn' writes violations to the MongoDB log, not to the application — easy to miss
  • Schema validation does not apply to existing documents unless you run a migration
  • Using additionalProperties: false blocks adding new fields — risky during rolling deployments
  • $jsonSchema inside validator does not support all JSON Schema features (e.g., $ref)

Code Snippets

Creating a collection with JSON Schema validation

db.createCollection('users', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['email', 'role'],
      properties: {
        email: { bsonType: 'string', pattern: '^[^@]+@[^@]+$' },
        role: { enum: ['admin', 'user', 'guest'] },
        age: { bsonType: 'int', minimum: 0, maximum: 150 }
      }
    }
  },
  validationAction: 'error',
  validationLevel: 'strict'
});

Revisions (0)

No revisions yet.