MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Built-in & Custom Schema Validations with Custom Error Messages0%
Study Materials
MongoDB & MongooseProgress 0%
1.1Document Databases vs Relational SQL: CAP Theorem & When to Use NoSQL1.2JSON vs BSON Data Types & MongoDB Internal Storage Engine (WiredTiger)1.3MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUI
3.1Mongoose Connection Lifecycle, Schemas & Compiled Models3.2Built-in & Custom Schema Validations with Custom Error Messages3.3Pre and Post Middleware Hooks (Document & Query Middleware)3.4Virtual Properties, Instance Methods & Static Model Methods
HomeTutorialsMongoDB & MongooseBuilt-in & Custom Schema Validations with Custom Error Messages
Pre and Post Middleware Hooks (Document & Query Middleware)

Built-in & Custom Schema Validations with Custom Error Messages

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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

ValidatorTarget TypesDescriptionExample
requiredAll typesEnsures field exists and is not nullrequired: [true, 'Email is mandatory']
min / maxNumber, DateEnforces minimum and maximum boundsmin: [0, 'Price must be positive']
minlength / maxlengthStringRestricts string character countminlength: [8, 'Password too short']
enumStringRestricts string to allowed array of valuesenum: ['draft', 'published', 'archived']
matchStringValidates string against a Regular Expressionmatch: [/^[\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:

1import { Schema, model } from 'mongoose';
2 
3const userSchema = new Schema({
4 name: {
5 type: String,
6 required: true
7 },
8 email: {
9 type: String,
10 required: true,
11 unique: true, // Note: unique creates a database index, not a validator!
12 validate: {
13 validator: function(v) {
14 return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(v);
15 },
16 message: props => `${props.value} is not a valid email address!`
17 }
18 },
19 discountPrice: {
20 type: Number,
21 validate: {
22 validator: function(val) {
23 // 'this' points to the current document being created
24 return val < this.price;
25 },
26 message: 'Discount price ({VALUE}) must be less than the regular price'
27 }
28 },
29 price: {
30 type: Number,
31 required: true
32 }
33});

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 }:

1const updatedCourse = await Course.findByIdAndUpdate(
2 courseId,
3 { price: -50 }, // Invalid!
4 {
5 new: true, // Return updated document
6 runValidators: true // Enforces schema validation rules!
7 }
8);

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
Why must { runValidators: true } be explicitly specified when calling findByIdAndUpdate() in Mongoose?
Question 2
Is unique: true in a Mongoose schema a validator?
Question 3
In a custom validator function, how do you access the value of the field being validated?
Question 4
Which built-in validator ensures that a String matches a predefined list of allowed choices?
Question 5
What type of error object is thrown when Mongoose validation fails?

Next Lesson

Pre and Post Middleware Hooks (Document & Query Middleware)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Mongoose Connection Lifecycle, Schemas & Compiled ModelsPre and Post Middleware Hooks (Document & Query Middleware)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master MongoDB & Mongoose with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext