1

I have asked this question .exec callback using returns is returning undefined, but console.log do have item in it

The answer does work, but it throws .exec away, I have been trying to re-implement it using .exec, however when I console.log something inside the .exec, it does print.

The reason I have been trying to use the .exec way is that a lot of StackOverflow questions use a lot .exec and I think ".exec" will be faster?

When I return it, it returns undefined. What is the cause and how can I solve it while keeping the .exec

let user = await User.findById(paymentBody.user_id)
.populate(User.schedule_table)
.exec((err, foundDocument) => {
  console.log(foundDocuments)
  return foundDocument;
});

console.log(user)

The code inside .exec (console.log(foundDocuments)), returns the result of query.

However, when I perform console.log(user) after the query, it shows undefined.

Wing Shum
  • 472
  • 6
  • 19
  • 1
    *I think ".exec" will be faster?* => no with and without both are equal, `.exec()` method just gives you better stack traces, nothing else. if you want to just return data I would suggest you to just use only `.exec()` don't add callback function. – turivishal Jun 06 '21 at 07:58
  • for handling error i would suggest you to use try-catch block, see the similar [question](https://stackoverflow.com/questions/66944226/in-mongoose-model-find-and-model-find-exec-produce-the-same-result-so-why) for the difference between with and without exec(), – turivishal Jun 06 '21 at 08:08

1 Answers1

0

You are mixing await and callbacks. Remove the callback and see if it works.

Will Walsh
  • 1,799
  • 1
  • 6
  • 15
  • Removing callback does work, is there anyway that it'll work without removing callback? I removed the await but it still returns undefined – Wing Shum Jun 06 '21 at 08:02
  • If you remove the await and leave the callback, you will need to take this into account, as in the current `console.log` after the query will still have `user` undefined as it runs before the callback. – Will Walsh Jun 06 '21 at 08:13