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.
this points to the document). Hooks: save, validate, remove, init.this points to the query). Hooks: find, findOne, findOneAndUpdate, countDocuments.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:
pre('save') document middleware hook, what does this keyword refer to?this.isModified('password') critical before hashing a password in a pre('save') hook?schema.pre(/^find/, ...) match?post('save') hook?next parameter callback style?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.