Skip to content

Data Modeling

Schema Validation

JSON Schema on a collection: required fields, types, and what happens to existing documents.

IntermediateAbout 5 minutes

MongoDB will store whatever you send. Validation is how a collection refuses the wrong shape anyway. It is JSON Schema ($jsonSchema), not Mongoose — that is a later module. Put rails on users so age cannot be a string and email cannot be missing.

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "city"],
      properties: {
        name: { bsonType: "string" },
        email: { bsonType: "string" },
        city: { bsonType: "string" },
        age: { bsonType: "int", minimum: 0 }
      }
    }
  },
  validationAction: "error",
  validationLevel: "strict"
})
Required fields and types. collMod adds this to a collection that already exists.
OptionMeaning
validationAction: errorReject the write (default)
validationAction: warnWrite anyway; log on the server — for a rollout
validationLevel: strictEvery insert and update is checked
validationLevel: moderateInserts always; updates of already-invalid docs can proceed

Existing documents are not rewritten when you attach a validator. moderate exists so a messy collection can keep serving while new writes are clean. Application checks are still required — the database rule is the backstop, not the form UX. validationAction: "warn" in production forever is how you get a schema nobody notices is failing.

Interview question

Does MongoDB have a schema? How do you enforce one?

Think about it first.