Not able to get my setup 404 status code, instead getting 500 status code for incorrect id

I am new to Nodejs and I am trying to play with the stuffs using using node js.

I created one api (using Nodejs, Express,Mongoose) to read users in which I am trying to search an Invalid user id(id is not matching with any records in the mongoDB).

The 404 response never triggers.I enter an incorrect ID and get 500.

Attaching the code screenshot for reference:

enter image description here

Upvotes: 0

Views: 87

Answers (2)

Amir BenAmara
Amir BenAmara

Reputation: 686

app.get('/useres/:id'), async (req, res) => {

    const _id = req.params.id;
    let user = await User.findById(_id).then((user) => {
        if (!user) {
            res.status(404).send()
        } else {
            res.status(200).json(user)
        }
    }).catch((e) => {
        res.status(500).send()
    })
}

Upvotes: 0

Amir Doreh
Amir Doreh

Reputation: 1429

for using findById you should pass only the id as a single value not in an object. so update your code as

User.findById(_id) 

and you are good to go

Upvotes: 2

Related Questions