advanced

Middleware

Use pre and post hooks carefully for cross-cutting persistence behavior without hiding business side effects.

Mongoose middleware runs before or after document, query, aggregate, or model operations. Common uses: timestamps, hashing passwords, audit fields—but hooks hide control flow.

| Hook scope | Triggers on | |------------|-------------| | Document | `save`, `remove`, etc. | | Query | `find`, `updateMany`, etc. |

On interviews: discuss pre/post hooks, document versus query middleware, error propagation, and why business workflows should stay visible in services.

Common pitfalls: operations that skip expected hooks; network or extra writes inside hooks breaking transactions; untested hook paths for the operation actually used in production.

The trade-off is centralized cross-cutting behavior versus debuggability.

Checklist:

  • Know hook type and trigger.
  • Keep side effects explicit.
  • Test middleware with the real operation path.
  • Avoid heavy work in hot query hooks.