MongoDB · Databasesadvanced

MongoDB $jsonSchema Validation

A MongoDB collection validator using $jsonSchema to enforce required fields, types and enums on a users collection — schema safety without an ORM.

mongodbschemavalidationjsonschemadatabase

Preview

{
  "$jsonSchema": {
    "bsonType": "object",
    "required": [
      "email",
      "createdAt"
    ],
    "additionalProperties": false,
    "properties": {
      "_id": {
        "bsonType": "objectId"
      },
      "email": {
        "bsonType": "string",
        "pattern": "^.+@.+$",
        "description": "must be a valid email and is required"
      },
      "role": {
        "bsonType": "string",
        "enum": [
          "admin",
          "member",
          "viewer"
        ],
        "description": "must be one of the allowed roles"
      },
      "age": {
        "bsonType": "int",
        "minimum": 0,
        "maximum": 120
      },
      "createdAt": {
        "bsonType": "date"
      }
    }
  }
}

AI actions

Documentation

Purpose

Enforce document structure at the database layer so malformed writes are rejected before they land.

When to use

Passed to db.createCollection(..., { validator }) or collMod to guarantee shape on a critical collection.

Required fields

  • $jsonSchema — the JSON Schema the documents must satisfy
  • bsonType — MongoDB's typed equivalent of JSON Schema "type"
  • required — the list of mandatory fields

Optional fields

  • properties — per-field type/constraint definitions
  • enum — allowed values for a field
  • additionalProperties — whether unknown fields are allowed

Best practices

  • Start with validationLevel "moderate" and action "warn", then tighten.
  • Use bsonType (not type) so ObjectId, Date and Decimal128 validate correctly.
  • Keep the validator in version control alongside migrations.

Security considerations

  • Validation is integrity, not authorization — pair with role-based access.
  • Reject additionalProperties on sensitive collections to block field injection.

Related templates