# Mongoose Validation — MongoDB

Source: https://www.geekswithgeeks.com/en/mongodb/mongo-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.

```javascript
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.

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

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

**Quiz:** What happens if a required field is missing when saving a Mongoose document?

- [ ] MongoDB silently fills in a default
- [x] 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.
