Schema validation

Make the collection refuse documents that do not meet a schema.

Make a collection refuse documents that do not meet a schema. Validators are MongoDB's, with query operators or $jsonSchema.

Requirements

  • A connection with a user that has readWrite on the database. To change the validator of an existing collection, dbAdmin.

Create the collection with its validator

JavaScript
db.createCollection("customers", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["email"],
      properties: { email: { bsonType: "string" } },
    },
  },
  validationLevel: "strict",
  validationAction: "error",
});

Change the validator of an existing collection

JavaScript
db.runCommand({ collMod: "customers", validator: { email: { $type: "string" } }, validationLevel: "moderate" });

validationLevel: "moderate" checks new documents and those that already complied; validationAction: "warn" lets the document in and records the warning.

Check

An insertOne without email fails with DocumentValidationFailure (121) while validationAction is error. With validationAction: "warn", the same insertOne goes into the collection and the warning is logged.

Common problems

  • Old documents that do not meet the schema still do not; with moderate, their updates are not checked.

See also