Built-in & Custom Schema Validations with Custom Error Messages
Built-in & Custom Schema Validations with Custom Error Messages
Data integrity starts at the model layer. Mongoose provides built-in validators for numbers, strings, dates, and arrays, as well as the ability to define asynchronous Custom Validators that enforce complex business rules before data reaches the database.
1. Built-in Mongoose Validators
| Validator | Target Types | Description | Example |
|---|---|---|---|
required | All types | Ensures field exists and is not null | required: [true, 'Email is mandatory'] |
min / max | Number, Date | Enforces minimum and maximum bounds | min: [0, 'Price must be positive'] |
minlength / maxlength | String | Restricts string character count | minlength: [8, 'Password too short'] |
enum | String | Restricts string to allowed array of values | enum: ['draft', 'published', 'archived'] |
match | String | Validates string against a Regular Expression | match: [/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/, 'Invalid email'] |
2. Writing Custom Asynchronous Validators
Custom validators use the validate property. You can supply a synchronous function, an asynchronous function returning a Promise/Boolean, or an async validator with custom error messages:
Note: In custom validators, this only points to the document on new document creation (.save()). For updates via findOneAndUpdate(), use { runValidators: true, context: 'query' }.
3. Triggering Validation on Updates
By default, Mongoose executes schema validators when creating documents via .save() or .create(). When running update queries like findByIdAndUpdate() or updateOne(), Mongoose skips validators by default for performance!
To force validation on updates, you must pass { runValidators: true }:
Multiple Choice Questions
{ runValidators: true } be explicitly specified when calling findByIdAndUpdate() in Mongoose?unique: true in a Mongoose schema a validator?Pre and Post Middleware Hooks (Document & Query Middleware)
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.