MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Pre and Post Middleware Hooks (Document & Query Middleware)0%
Study Materials
MongoDB & MongooseProgress 0%
1.1Document Databases vs Relational SQL: CAP Theorem & When to Use NoSQL1.2JSON vs BSON Data Types & MongoDB Internal Storage Engine (WiredTiger)1.3MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUI
3.1Mongoose Connection Lifecycle, Schemas & Compiled Models3.2Built-in & Custom Schema Validations with Custom Error Messages3.3Pre and Post Middleware Hooks (Document & Query Middleware)3.4Virtual Properties, Instance Methods & Static Model Methods
HomeTutorialsMongoDB & MongoosePre and Post Middleware Hooks (Document & Query Middleware)
Virtual Properties, Instance Methods & Static Model Methods

Pre and Post Middleware Hooks (Document & Query Middleware)

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Mongoose middleware (also referred to as Pre and Post Hooks) allows developers to execute logic automatically during the lifecycle of a document or query. Pre/Post hooks are essential for automated password hashing, slug generation, cascading deletes, and query filtering.


1. Document Middleware vs Query Middleware

  • Document Middleware: Operates on the individual document instance (this points to the document). Hooks: save, validate, remove, init.
  • Query Middleware: Operates on a Mongoose query object (this points to the query). Hooks: find, findOne, findOneAndUpdate, countDocuments.

2. Document Middleware Example: Slug Generation & Password Hashing

1import { Schema, model } from 'mongoose';
2import slugify from 'slugify';
3import bcrypt from 'bcrypt';
4 
5const userSchema = new Schema({
6 name: String,
7 email: String,
8 password: {
9 type: String,
10 required: true,
11 select: false // Exclude password from query results by default
12 },
13 slug: String
14});
15 
16// PRE-SAVE HOOK: Automatically hash password if modified
17userSchema.pre('save', async function(next) {
18 // Only run if password field was modified (or created)
19 if (!this.isModified('password')) return next();
20 
21 // Hash password with cost factor of 12
22 this.password = await bcrypt.hash(this.password, 12);
23 next();
24});
25 
26// PRE-SAVE HOOK: Automatically generate URL slug from name
27userSchema.pre('save', function(next) {
28 if (this.isModified('name')) {
29 this.slug = slugify(this.name, { lower: true, strict: true });
30 }
31 next();
32});

3. Query Middleware Example: Soft-Delete Auto-Filter

To implement "soft deletes" (hiding deleted records rather than permanently deleting them), use a pre(/^find/) regex hook to automatically filter out soft-deleted documents on all find queries:

1// Automatically exclude soft-deleted documents from any find, findOne, etc.
2courseSchema.pre(/^find/, function(next) {
3 // 'this' refers to the Query object
4 this.find({ isDeleted: { $ne: true } });
5 this.start = Date.now();
6 next();
7});
8 
9// POST-FIND HOOK: Measure and log query duration
10courseSchema.post(/^find/, function(docs, next) {
11 const elapsed = Date.now() - this.start;
12 console.log(`Query completed in ${elapsed}ms`);
13 next();
14});

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
In a Mongoose pre('save') document middleware hook, what does this keyword refer to?
Question 2
Why is checking this.isModified('password') critical before hashing a password in a pre('save') hook?
Question 3
What does regex middleware schema.pre(/^find/, ...) match?
Question 4
What parameters are passed to a post('save') hook?
Question 5
What must you call at the end of asynchronous middleware if you use the next parameter callback style?

Next Lesson

Virtual Properties, Instance Methods & Static Model Methods

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Built-in & Custom Schema Validations with Custom Error MessagesVirtual Properties, Instance Methods & Static Model Methods

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master MongoDB & Mongoose with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext