1

I know there are other posts with similar issues, but none of the suggestions I've tried have worked.

The following works if the _id is valid, but throws an unhandled promise rejection error if it isn't:

const Movie = mongoose.model(`Movie`, movieSchema);


router.get(`/api/movies/:id`, async (req, res) => {
    let movie = await Movie.findById(req.params.id);

    if(!movie) {
        res.status(404).send(`Movie with given ID not found.`);
        return;
    };
});

Per the docs, it looks like findById() is supposed to return null if the id can't be found, so I'm not sure what the issue is. Do I need to put a catch block somewhere and put the 404 in there? I've tried putting it everywhere I can think to.

William
  • 77
  • 8

2 Answers2

0

As per the Mongoose documentation...

Model.findById()

Returns:

  • «Query»

Looking into the Query API, when used like a Promise, it will invoke the Query.prototype.then() implementation

Executes the query returning a Promise which will be resolved with either the doc(s) or rejected with the error.

To use this, you would need something like

try {
  const movie = await Movie.findById(req.params.id)
  // do stuff with movie
} catch (err) {
  res.sendStatus(404)
}
Phil
  • 157,677
  • 23
  • 242
  • 245
  • I tried this too, same result. I should've mentioned this though, good shout. – William Aug 17 '21 at 01:51
  • Tried what? There are two code snippets in my answer – Phil Aug 17 '21 at 01:52
  • I tried using let movie = await Movie.findById(req.params.id).exec(); – William Aug 17 '21 at 01:52
  • @William the docs for the return value of `exec()` aren't super clear (it just says `«Promise»`, not very helpful) but it seems perhaps that code comment mentioning `null` isn't accurate. I would go with the `try..catch` implementation – Phil Aug 17 '21 at 01:55
-1

use .then() and .catch() will sort your issue.