tezvyn:

Mongoose Middleware (Hooks): Intercepting Database Operations

Source: mongoosejs.comintermediate

Mongoose middleware (hooks) lets you intercept database operations. Think of them as "before" or "after" scripts for actions like `save` or `find`. Use them to hash passwords before saving a user.

Mongoose middleware, or hooks, lets you define functions that run before (`pre`) or after (`post`) a database operation. It's like setting up checkpoints in your data's lifecycle to run custom logic, such as hashing a password before saving a user or cleaning up related records after a delete. The most common footgun is misunderstanding `this`: in document middleware (`save`), `this` is the document, but in query middleware (`findOneAndUpdate`), `this` is the query object, not the document being modified.

Read the original → mongoosejs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

Mongoose Middleware (Hooks): Intercepting Database Operations · Tezvyn