node.js & mongodb: await collection.find vs. collection.find.exec for async

Viewed 726

I recently came across the node.js/mongodb pattern which as I understand returns a promise. collection.find({ ... }).exec()

I use in my code:

await collection.find({ ... })

How are these different? Should I be using:

await collection.find({ ... }).exec()

Here's what I currently use and it works w/o issue:

router.get('/me', auth, async (req, res) => {
        const user = await User.findById(req.user.sub).select('email');

        if (!user) return res.status(400).json({ "status": "error", "message": "This user no longer exists." });

        res.json({ "status": "success", "user": user });
});
1 Answers

In Mongoose queries are composed but not necessarily run immediately.They return a query object that you can use to add or chain other queries to it and then execute it all together.

Mongoose queries are not promises. They have a .then() function and async/await as a convenience.. .exec() can be used instead of .then() too for a callback.

Which one you should use?

  • await collection.find({ ... })
  • await collection.find({ ... }).exec()

Answer : Both are fine.

Both does have some functionality so you can use any of the two as per your convenience.

However, if you use .exec() it will give you better stack traces in case of errors/exceptions. More information here.

Related