Lesson 18 / 22

Mongoose Validation

Enforce required fields, ranges, and allowed values.

Built-in validators

required, min/max, and enum are common built-in validators you can attach per field.

const productSchema = new Schema({
  name: { type: String, required: true },
  price: { type: Number, min: 0 },
  status: { type: String, enum: ["active", "discontinued"] }
});

A validation error

Missing a required field throws a ValidationError before anything reaches the database.

const Product = model("Product", productSchema);

try {
  await Product.create({ price: 50 }); // missing name
} catch (err) {
  console.log(err.name); // "ValidationError"
}

Quick check: What happens if a required field is missing when saving a Mongoose document?

  • MongoDB silently fills in a default
  • A ValidationError is thrown and nothing is saved
  • The field is saved as null
Answer

A ValidationError is thrown and nothing is saved — Mongoose validates before hitting the database — a required-field violation rejects the save.