

Discover more from Ayoub’s Newsletter
How the heck does Mongoose Middleware work?
Understand how Mongoose Middleware – A key for your data consistency – works with illustrative diagrams.
Hey there, 🖐️
Have you ever scratched your head over Mongoose Middleware, aka Hooks, and wondered how it works? You're not the only one.
It's a cool Mongoose feature that can seriously up your app game. Middleware allows you to run specific functions before or after a Mongoose operation, which is super helpful for things like data validation or encryption. 🔒
Let's take the classic "Delete on Cascade" dilemma. Say you have a User
model that stores all your app's user data. Each user has authored multiple articles which belong to a Post
model. When you delete a user, you probably don't want their articles to linger in your database, right? You may be tempted to manually delete these articles whenever you remove a user, quickly leading to messy, duplicated code. Not to mention that you can easily forget to set it here and there, which can lead to data inconsistency.
Solution? You can create a post('deleteOne')
middleware – a Javascript function – and drop your article deleting logic there, and you're golden. When you delete a user (from anywhere in your codebase), Mongoose automatically triggers this middleware and cleans up those articles. Think of it as your database's own virtual assistant.
Here's a sample code of how you can achieve this:
UserSchema.post('deleteOne', async function() {
await Post.deleteMany({ author: this._id });
});
That's just scratching the surface, honestly.
If you're interested in learning more about Mongoose Middleware, Check out my recently published article, which demystifies all the middleware types and how they differ, with a couple of real-world examples.
That's all, folks! Hope everyone is having a lovely weekend start. If you have any questions in mind or any feedback, send me a message on Twitter or reply to this email! I'd love to hear from you.
Warm wishes,