QA
Beginner LevelMongoDB & Mongoose

How does Mongoose handle built-in and custom schema validation?

❓ Interview Prompt: Explain built-in validators (required, min, max, enum, match), custom validator functions, and handling ValidationError exceptions.

Mongoose evaluates schema validation rules in Node.js before sending write commands to MongoDB:

Built-in Validators:

•
String: 'required', 'enum', 'minlength', 'maxlength', 'match' (regex).
•
Number: 'min', 'max'.

Custom Validators:

Pass a 'validate' object with a validator function returning boolean or Promise.

Code Implementation Example

typescript
import { Schema } from 'mongoose';

const userSchema = new Schema({
  username: {
    type: String,
    required: [true, 'Username is required'],
    minlength: 3
  },
  role: {
    type: String,
    enum: ['USER', 'ADMIN', 'MODERATOR'],
    default: 'USER'
  },
  age: {
    type: Number,
    validate: {
      validator: (v: number) => v >= 18,
      message: 'User must be at least 18 years old'
    }
  }
});
💡Defining Mongoose built-in and custom schema validation rules.
🎯 Interview Key Takeaway

Use Mongoose schema validation to catch bad input data in Node.js before executing database operations.

#Validation#Mongoose#Schema#Beginner
Back to all MongoDB & Mongoose Questions→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?