Magic of Mongoose Middlewares

Nadia Sultana
2 min readFeb 1, 2024

--

Mongoose Middlewares — the incredible tools that add sorcery to your database interactions by giving a layer of customization that goes beyond the ordinary. This piece offers a behind-the-scenes look at Mongoose’s secret spells, where every line of code has the power to influence the life cycle of your data. So, grab your wand (or keyboard), and let’s uncover the secrets together!

Understanding Mongoose Middlewares

Mongoose middlewares are methods that allow you to inject custom logic into a Mongoose document at various stages of its lifecycle. You can customize behavior for your application, such as saving, updating, deleting, or verifying data.

Pre-Save Middleware

Consider a scenario where you want to automatically generate a unique username for a new user before saving it to the database. Here’s how you can employ the pre-save middleware:

userSchema.pre('save', function (next) {
if (!this.username) {
this.username = generateUniqueUsername(); // logic for generating a unique username
}
next();
});

With this middleware, every time a new user document is saved, if the username is not provided, it dynamically generates one before saving it to the database.

Pre-Update Middleware

Let’s say you want to log the timestamp of the last update every time a user document is updated. The pre-update middleware comes to the rescue:

userSchema.pre('updateOne', function (next) {
this.update({}, { $set: { lastUpdate: new Date() } });
next();
});

This middleware triggers before the updateOne operation, allowing you to inject additional update operations — in this case, updating the lastUpdate field.

Post-Remove Middleware

When a document is removed from the database, you might want to perform additional cleanup actions.

Let’s say you have a user schema and a blogpost schema that has author_id reference to user. If a user deletes their account from your website you would want to delete all their blogs as well, right? Here’s how you can use post-remove middleware to do exactly that:

userSchema.post('remove', async function (doc, next) {
try {
// Find and remove all blog posts associated with the deleted user
await mongoose.model('BlogPost').deleteMany({ author_id: doc._id });

console.log(`User ${doc.username} and associated blog posts have been deleted.`);
next();
} catch (error) {
console.error('Error cleaning up associated blog posts:', error);
next(error);
}
});

To sum up, Mongoose middlewares are the secret sauce that can take your MongoDB experience to new heights giving you unparalleled control and customization over your database. Happy coding!

--

--