Search code examples
node.jsmongodbasynchronousmongooseunhandled-promise-rejection

Mongoose: Unhandled promise rejection


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.


Solution

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