Reputation: 1
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:
Upvotes: 0
Views: 87
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
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