Mongoose: Unhandled promise rejection

Viewed 117

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.

2 Answers

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)
}

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

Related