2.5 Hours

11. Advanced Mongoose

ODM

Advanced Mongoose Features

Mongoose provides powerful features beyond basic CRUD: validation, middleware (hooks), virtual properties, and population (JOIN-like operations).

Schema Validation

Validation rules ensure data quality before saving. You can require fields, set minimum/maximum values, match patterns with regex, or restrict values to an enum list. If validation fails, Mongoose throws a ValidationError.

JavaScript
const userSchema = new mongoose.Schema({
    email: {
        type: String,
        required: [true, 'Email is required'],
        unique: true,
        lowercase: true,
        match: [/^\S+@\S+\.\S+$/, 'Invalid email']
    },
    age: {
        type: Number,
        min: [13, 'Must be at least 13'],
        max: [120, 'Age too high']
    },
    role: {
        type: String,
        enum: ['user', 'admin', 'moderator'],
        default: 'user'
    }
});

Middleware (Hooks)

Middleware functions run before or after certain operations like save, validate, or remove. Pre-save middleware is perfect for hashing passwords automatically. The document is this inside the middleware.

JavaScript
const bcrypt = require('bcrypt');

const userSchema = new mongoose.Schema({
    email: String,
    password: String
});

userSchema.pre('save', async function(next) {
    if (!this.isModified('password')) return next();
    
    this.password = await bcrypt.hash(this.password, 12);
    next();
});

userSchema.post('save', function(doc) {
    console.log(`User ${doc.email} was saved`);
});

Virtual Properties

Virtuals are properties that are NOT stored in the database. They are computed on the fly when you access them. This is useful for combining fields like firstName and lastName into fullName without storing redundant data.

JavaScript
const userSchema = new mongoose.Schema({
    firstName: String,
    lastName: String
});

userSchema.virtual('fullName').get(function() {
    return `${this.firstName} ${this.lastName}`;
});

const User = mongoose.model('User', userSchema);
const user = new User({ firstName: 'John', lastName: 'Doe' });
console.log(user.fullName); // 'John Doe' - not stored, just computed

Population (Relationships)

Population automatically replaces reference IDs with the actual documents they point to. This is like a SQL JOIN but for MongoDB. A Post document has an author field that stores a User ID. populate() replaces that ID with the full User document.

JavaScript
const postSchema = new mongoose.Schema({
    title: String,
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});

const Post = mongoose.model('Post', postSchema);

const posts = await Post.find().populate('author', 'name email');
console.log(posts[0].author.name); // Access the author's name directly

Query Helpers & Chaining

Mongoose queries are chainable. You can add .where(), .limit(), .sort(), .select() to build complex queries. The .lean() method returns plain JavaScript objects instead of Mongoose documents, which is faster when you don't need document methods.

JavaScript
const users = await User
    .find({ active: true })
    .where('age').gt(18)
    .sort('name')
    .limit(10)
    .select('name email age');

const fastUsers = await User.find().lean();

const count = await User.countDocuments({ active: true });
const exists = await User.exists({ email: 'test@test.com' });

Knowledge Check

Ready to test your understanding of 11. Advanced Mongoose?

Back