3

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 });
});
Gary
  • 909
  • 9
  • 26
  • Does this answer your question? [Mongoose - What does the exec function do?](https://stackoverflow.com/questions/31549857/mongoose-what-does-the-exec-function-do) – Viraj Singh Jul 31 '20 at 17:35
  • It does, but what's confusing is that my routine works perfectly and I don't use ".exec()" and await. I'll update the question w/my exact code. – Gary Aug 01 '20 at 00:06

1 Answers1

3

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.

Deekshith Hegde
  • 1,318
  • 2
  • 15
  • 27