0

When the document with the given id is not found, the catch block gets executed. But when document is not found, then findById returns null and so it should send 404 and not 500 status code.

app.get('/users/:id', (req, res) => {
    const _id = req.params.id;

    User.findById(_id).then((user) => {
       if (!user) {
           return res.status(404).send()
       }

       res.send(user)
    }).catch((error) => {
       res.status(500).send()
    })
})
Thanks
  • 1
  • 1
  • Your query looks good, event i run your code and its working properly, please check other possibilities. – turivishal May 01 '21 at 10:30
  • One possibility is the _id parameter isn't a valid ObjecId, which is expected by the `findById` function. Your problem looks like this one: https://stackoverflow.com/questions/67246104/mongoose-defining-404-status-for-not-finding-a-document-doesnt-work/67247073#67247073 – Đăng Khoa Đinh May 01 '21 at 13:18
  • It'd be nice if you could provide the error message in the catch block too. – thealpha93 May 02 '21 at 05:44
  • @ĐăngKhoaĐinh Thanks a lot, it was happening because of invalid ObjectId. Also thanks to everyone for the response. – Thanks May 03 '21 at 00:52

0 Answers0