Schema Validation & Defaults
Make Mongoose enforce your data rules so bad data never reaches the database.
What you will learn
- Add validation rules to a schema
- Set defaults and required fields
- Understand server-side data integrity
Rules in the schema
Schemas can enforce rules — required fields, types, min/max, allowed values, defaults — so invalid data is rejected automatically.
const productSchema = new mongoose.Schema({
name: { type: String, required: true, trim: true },
price: { type: Number, required: true, min: 0 },
category: { type: String, enum: ["tech", "books", "food"] },
inStock: { type: Boolean, default: true },
createdAt: { type: Date, default: Date.now }
});Each field carries its own rules. name is required text and trim: true strips stray spaces around it. price must be a number and min: 0 forbids negatives. category uses enum (short for *enumeration* — a fixed list of allowed values) to allow only one of three exact words, "tech", "books" or "food" — anything else is rejected. inStock defaults to true and createdAt defaults to the current time, so you do not have to set them yourself. These rules run automatically every time you try to save.
Here is a concrete example. Suppose a request tries to save this product:
// A bad product the client tried to send
await Product.create({ price: -5, category: "toys" });This breaks three rules at once: name is missing (but required), price is -5 (below min: 0), and category is "toys" (not in the enum list). So Mongoose refuses to save it and throws a validation error instead — nothing reaches the database.
Step by step, here is the validation flow every save goes through:
- Your code calls a save method, e.g.
Product.create({ ... })with the incoming data. - Mongoose checks the data against every rule in the schema (required, type,
min,enum, and so on). - If all rules pass, the document is written to MongoDB and returned to you.
- If any rule fails, Mongoose throws a validation error and writes nothing.
- Your
try/catchcatches that error and you reply with a400status (the HTTP code for “Bad Request”) so the client knows the data was rejected and why.
Note: If you try to save a document that breaks the rules (missing name, negative price, invalid category), Mongoose throws a validation error before anything touches the database. Catch it and return a 400 — the HTTP status code meaning “Bad Request” — to the client.
Tip: This is your second line of defence: HTML validation helps users, but the server/schema validation is what truly protects your data. Never rely on the front-end alone.
Q. What happens if you save a document that violates the schema rules?
✍️ Practice
- Add
required,minand adefaultto a schema and test saving invalid data. - Use an
enumto restrict a field to a few allowed values.
🏠 Homework
- Add thorough validation to your blog
Postschema.