Mongodb Guide

How to Apply Validation in Mongoose

1. Definition

Validation in Mongoose ensures that data stored in MongoDB follows specific rules defined in the schema. It helps maintain data integrity and prevents invalid data from being saved.

2. Simple Understanding

👉 Validation = rules for data
👉 Example: name is required, age must be a number
👉 If rules fail → data is not saved

3. When to Use

  • When saving user data
  • When ensuring required fields
  • When restricting invalid input
  • When building secure APIs

4. Where it is Used

  • Schema definition
  • Backend validation layer
  • API request validation
  • Database data integrity

5. Why We Use It

  • Prevents invalid data
  • Improves data quality
  • Reduces bugs
  • Ensures consistent database structure

6. How It Works

  • Define rules inside schema
  • Mongoose checks before saving
  • If validation fails → error is thrown
  • If passes → data is saved

7. Types of Validation

  • required → Field must be present
  • min / max → Number limits
  • minLength / maxLength → String length
  • enum → Allowed values
  • match → Regex validation

8. Basic Syntax

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 3
  },
  age: {
    type: Number,
    min: 18,
    max: 60
  },
  email: {
    type: String,
    required: true,
    match: /.+\@.+\..+/
  }
});

9. Real Example

const User = mongoose.model("User", userSchema);

// Invalid data (will throw error)
const user = new User({
  name: "A",
  age: 10,
  email: "invalid"
});

user.save().catch(err => console.log(err.message));

10. Explanation

  • name must be at least 3 characters
  • age must be between 18 and 60
  • email must match regex pattern
  • If any rule fails → error occurs

11. Advantages

  • Ensures valid data
  • Improves security
  • Reduces bugs
  • Automatic validation

12. Disadvantages

  • Extra processing overhead
  • Complex rules can be hard to manage

Interview Points

  • Validation is defined in schema
  • Prevents invalid data
  • Common rules: required, min, max, match
  • Runs before saving data