Skip to main content

Command Palette

Search for a command to run...

Day 27: Validations and Custom Schema Types

Published
β€’6 min read
P
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: πŸš€ In-depth explorations of emerging technologies πŸ’‘ Practical tutorials and how-to guides πŸ”§Insights on software development best practices πŸš€Reviews of the latest tools and frameworks πŸ’‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟

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, $in

  • Sorting 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?

FilteringSorting
Decides which data to showDecides order of data
Uses operators like $gt, $inUses .sort()
Example: price < 500Example: 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...catch

  • Express 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:

  1. Create Student schema with:

    • name

    • age

    • course

    • marks

  2. 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:

  1. 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:

  1. Show only 3 students per page

  2. 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. πŸš€

More from this blog

T

Technologies: Tools & Tips | Expert Guides on Latest Tech Tools

125 posts