Hooks in MongoDB and How to Use Them

Hooks in MongoDB and How to Use Them

Did you know that you can use hooks in MongoDB? Or were you also surprised after reading the title of this blog, like I was when I found out about this? Read along.

Well, the hooks are not exactly in MongoDB, but they are actually middleware functions provided by the Mongoose library. There are two kinds of hooks/middleware: pre and post.

Pre Hooks

The pre hook in Mongoose, just as it sounds, lets us define what we want to do before a specific event takes place. For instance, assume a schema UserSchema has already been defined, then what do you think the following code does?

UserSchema.pre('save', function(next) {
    console.log("The document will be saved after printing this.");
    next();
})

Yes, you're correct! When a document is about to be saved, Mongoose will first run the above function and then save the document to the database, hence the name 'pre' hook.

Here, 'save' is an event which defines that what will be the operation which will be performed after the function has been executed.

The function, next(), is a function which, on calling, will proceed to the next action in line, which is, in our case, saving the document. If next() isn't called anywhere in this function, this function will be executed properly, but the next steps won't be executed and hence the server will be stuck.

Post Hooks

The post hook, as you might have guessed, is similar to the pre hook, but here the function runs after the specified operation is performed.

Based on this knowledge, can you now guess the output of the following code?

UserSchema.post('save', function(next) {
    console.log("The document has been saved in the database.");
    next();
})

Again, you're correct! Mongoose will first save the document in the database, and then it will run this function and print the given output.

Applications

Now that you know about middleware in Mongoose, you may wonder where we might need these hooks. Here's an example :

Imagine that you are building authentication for your web app. You would want to hash the password before you store it in the database so that the passwords of users remain secure. You can use a pre save hook to achieve this easily. Also, it would be a good user experience if the user gets an email after signing up to your website. A post save hook would be useful for this purpose.

This example is the one given in the cover image of this blog, which is an image from freeCodeCamp.

There are a lot of other events/operations that can be specified other than 'save', like 'validate', 'findOneAndUpdate', 'remove' and many more. You may look at the following link to learn more about these hooks/middleware.