Use Mongoose with Promises
I have been working with Node.js for more than 2 years and one of the first things you learn since the beginning is that callbacks sucks. Callbacks are the consequence of asynchronous operations. And when we nest several of them (we usually need to do it), we fall in the problem known as callback hell. It means the code becomes less readable, harder to maintain and even less efficient.
In this post, we are going to see how to use promises with Mongoose to avoid callbacks. Mogoose is an important ODM that allows us to use MongoDB in Node.js. The problem is, the most of the examples I found on the web use callback style. Let’s see the following example:
We have defined the simplest schema to store users. Now, let’s do some queries:
Now, let’s say we want to find a user to ban it. We could do it in just one operation with the method update in the model, but that way we will not see how good promises are. So, let’s do it in 2 steps:
To start, we can see the variable error in the 2 callbacks, what means that we loose the value of the first one in the second callback. We could solve it renaming the variables with something like: error1 and error2, but this is not elegant. And, what happen if we have more nested callbacks? Let’s imagine the next scenario:
Yes, we get a callback hell case! Now, it comes the main reason of this post: using Mogoose with promises. We are going to add to our schema the next statics methods (where we will use promises):
Now we can do something like:
In the code above, we create the first query and we chain the rest via promises. If any promise in the chain gets an error, the flow automatically goes to the catch function.
Of course, for using promises with Monogoose is not necessary to define them as static methods in the schema definition, but for me, this way is pretty clear and useful.
We can also execute promises in parallel if there is no dependency among them. For example:
As result, our final code is much more readable, maintainable and elegant (even more efficient in certain cases where callback hell can produce memory leaks).