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.
| 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'] |
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' }.
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 }:
{ runValidators: true } be explicitly specified when calling findByIdAndUpdate() in Mongoose?unique: true in a Mongoose schema a validator?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.