Mongoose & the Full StackExtra· 30 min read

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.

Validation, enums and defaults
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:

Three rules are broken at once
// 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:

  1. Your code calls a save method, e.g. Product.create({ ... }) with the incoming data.
  2. Mongoose checks the data against every rule in the schema (required, type, min, enum, and so on).
  3. If all rules pass, the document is written to MongoDB and returned to you.
  4. If any rule fails, Mongoose throws a validation error and writes nothing.
  5. Your try/catch catches that error and you reply with a 400 status (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?

Answer: Mongoose validates against the schema and throws a validation error, which you handle and return as a 400 — keeping bad data out.

✍️ Practice

  1. Add required, min and a default to a schema and test saving invalid data.
  2. Use an enum to restrict a field to a few allowed values.

🏠 Homework

  1. Add thorough validation to your blog Post schema.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →