Data Modeling
Schema Validation
JSON Schema on a collection: required fields, types, and what happens to existing documents.
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"
})| Option | Meaning |
|---|---|
| validationAction: error | Reject the write (default) |
| validationAction: warn | Write anyway; log on the server — for a rollout |
| validationLevel: strict | Every insert and update is checked |
| validationLevel: moderate | Inserts 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?
Documents are flexible by default. You enforce a shape with collection validation — $jsonSchema, required fields, bsonTypes. validationAction error rejects bad writes; warn logs them. Existing documents are not rewritten when you add a validator. App-level schemas (Mongoose) are a second layer, not a substitute if other clients can write.