Day 27: Validations and Custom Schema Types
MongoDB itself is schema-less, but Mongoose adds schema and validation support. This ensures data stored in your database follows correct format and rules.
πΉ 1. Built-in Validations in Mongoose
Mongoose allows adding validations directly inside schema fields.
Example
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true, // must be present
minlength: 3,
maxlength: 50
},
age: {
type: Number,
min: 18, // minimum allowed
max: 60
},
email: {
type: String,
required: true,
unique: true,
match: /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/ // regex for email format
},
createdAt: {
type: Date,
default: Date.now
}
});
const User = mongoose.model("User", userSchema);
πΉ 2. Custom Validation
If built-in rules are not enough, you can write your own validation function.
const productSchema = new mongoose.Schema({
name: String,
price: {
type: Number,
validate: {
validator: function (value) {
return value > 0; // price must be positive
},
message: "Price must be greater than 0"
}
}
});
const Product = mongoose.model("Product", productSchema);
πΉ 3. Custom Schema Types
Sometimes you want to enforce specific data format.
Example β A schema type for phone numbers.
const customerSchema = new mongoose.Schema({
phone: {
type: String,
validate: {
validator: function (v) {
return /^[0-9]{10}$/.test(v); // must be 10 digits
},
message: "Phone number must be 10 digits"
}
}
});
π― Real-life Example: Hotel Booking
Validation: Guest name required, age β₯ 18, check-in date must be before check-out date.
Custom Type: Phone number must be 10 digits, email must be valid.
const bookingSchema = new mongoose.Schema({
guestName: { type: String, required: true },
age: { type: Number, min: 18 },
email: { type: String, required: true, match: /^[^@]+@[^@]+\.[^@]+$/ },
phone: { type: String, validate: /^[0-9]{10}$/ },
checkIn: { type: Date, required: true },
checkOut: { type: Date, required: true }
});
// custom validation for dates
bookingSchema.path("checkOut").validate(function (value) {
return value > this.checkIn;
}, "Check-out date must be after check-in date");
π Why Validations Matter?
Protects your database from bad data
Saves developers from unexpected bugs later
Ensures data integrity (clean + reliable data)
β Summary
Day 26
Filtering with operators like
$gt,$lt,$inSorting results with
.sort()Pagination using
.skip()+.limit()
Day 27
Built-in validations (
required,min,max,match)Custom validations with validator functions
Custom schema types (like phone numbers, dates, etc.)
π Day 26 & Day 27 β FAQ + Practice Tasks
β FAQ Section (Studentsβ Common Doubts)
1οΈβ£ What is the difference between find() and query operators like $gt, $lt?
π find() is used to fetch data from MongoDB.
π Query operators are conditions you pass inside find() to filter data.
Example:
Student.find({ age: { $gt: 18 } })
This means:
βFind students whose age is greater than 18β
So:
find()β action$gt,$lt,$inβ filtering rules
2οΈβ£ Can we use multiple filters together?
β Yes, and this is very common in real projects.
Example:
Student.find({
age: { $gte: 18 },
course: "Math"
})
β Finds students:
age β₯ 18
AND course = Math
MongoDB automatically applies AND condition.
3οΈβ£ What is the difference between sorting and filtering?
| Filtering | Sorting |
| Decides which data to show | Decides order of data |
Uses operators like $gt, $in | Uses .sort() |
| Example: price < 500 | Example: price low β high |
Example:
Product.find({ price: { $lt: 500 } }).sort({ price: 1 })
4οΈβ£ Why pagination is important? Canβt we just use find()?
β In small projects, yes.
β In real apps, NO.
Reasons:
Too much data β slow API
High memory usage
Bad user experience
Pagination helps:
Faster response
Clean UI (page wise data)
Scalable applications
5οΈβ£ What is the real meaning of skip() and limit()?
.skip(10).limit(5)
Means:
Skip first 10 records
Return next 5 records
Used in:
- Page 2, Page 3, Page 4β¦ systems
6οΈβ£ Is validation only for frontend?
β No. Frontend validation can be bypassed.
β Backend validation is mandatory because:
API can be called from anywhere
Data safety is backend responsibility
Best practice:
β Frontend validation
β Backend validation (Mongoose)
7οΈβ£ What happens if validation fails?
Mongoose throws an error, for example:
{
"message": "User validation failed: age must be greater than 18"
}
This error should be handled using:
try...catchExpress error middleware
8οΈβ£ Can we use custom validation in real projects?
β Absolutely yes.
Used for:
Password rules
Phone number format
Date comparisons
Business logic rules
9οΈβ£ Does validation affect database performance?
β Very little impact
β
Huge benefit in data quality
So always use validations.
π Are these concepts used in real companies?
π― YES.
Filtering β dashboards, reports
Sorting β latest data first
Pagination β product listing
Validation β every form & API
π§ͺ Mini Exercise Tasks (Hands-On Practice)
These tasks are designed so students can practice without copying code, and actually think like developers.
π’ Task 1: Student Filter API
Goal:
Create an API to filter students.
Requirements:
Create
Studentschema with:name
age
course
marks
Create API:
Get students whose age > 18
Get students with marks β₯ 60
Get students from βScienceβ course
π Hint:
Use $gt, $gte
π’ Task 2: Sorting Challenge
Goal:
Sort student records.
Requirements:
Sort students by:
marks (high β low)
name (A β Z)
π Hint:
.sort({ marks: -1 })
.sort({ name: 1 })
π’ Task 3: Pagination Implementation
Goal:
Show students page by page.
Requirements:
Show only 3 students per page
Use URL like:
/students?page=1
/students?page=2
π Bonus:
Add default page if page not provided.
π’ Task 4: Validation Practice
Goal:
Protect database using validations.
Add validations:
name β required, min 3 characters
age β min 18
email β valid email format
marks β between 0 and 100
π Try inserting wrong data and observe error.
π’ Task 5: Custom Validation (Advanced)
Goal:
Create business logic validation.
Scenario:
Hotel Booking
Rules:
checkOut date must be after checkIn
phone number must be exactly 10 digits
π Implement custom validator functions.
π₯ Bonus Challenge (For Strong Students)
Build an API:
GET /students/search
Features:
Filter by course
Sort by marks
Pagination enabled
Validations applied in schema
π This is real-world interview-level practice.
β What Students Will Learn After These Tasks
β How real APIs handle large data
β Clean database design
β Writing production-ready schemas
β Thinking beyond βjust CRUDβ
π Stay Connected
If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas β π© Subscribe to our newsletter by entering your email below.
And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, π₯ Donβt forget to subscribe to my YouTube channel β Knowledge Factory 22 β for regular content on tech concepts, career tips, and coding insights!
Stay curious. Keep building. π

