How does MongoDB handle schema validation?
Answer
MongoDB supports optional schema validation using JSON Schema, allowing you to enforce document structure while retaining flexibility. Creating a collection with validation: db.createCollection("users", { validator: { $jsonSchema: { bsonType: "object", required: ["name", "email"], properties: { name: { bsonType: "string", description: "must be a string and is required" }, email: { bsonType: "string", pattern: "^.+@.+$", description: "must be a valid email" }, age: { bsonType: "int", minimum: 0, maximum: 120 }, tags: { bsonType: "array", items: { bsonType: "string" } } } } }, validationLevel: "strict", validationAction: "error" }). Validation levels: strict (default): validates all inserts and updates; moderate: validates inserts and updates to existing valid documents (skips pre-existing invalid documents). Validation actions: error (default): rejects invalid documents; warn: allows invalid documents but logs a warning — useful for migrating existing data. Adding validation to existing collection: db.runCommand({ collMod: "users", validator: {...}, validationLevel: "strict" }). Check validation errors: when validation fails, the error message includes which schema rule was violated. Using Mongoose (ODM): Mongoose adds application-level schema validation for Node.js, which is more developer-friendly and runs before the database. Best practice: use both Mongoose validation (developer experience) and MongoDB validation (database-level guarantee).
Previous
What is the MongoDB aggregation $bucket and $bucketAuto stage?
Next
What is the $facet stage in MongoDB aggregation?