I am writing a express endpoint to get me a user credentials from my mongoDB database using the email but i am getting back a 404 error when i test the endpoint with postman here is the code
/**GET: http://localhost:9000/api/user/[email protected] */ //url endpoint
export async function getUser(req, res){
const { email } = req.params;
try {
if(!email) return res.status(501).send({ error: "Invalid Username"})
UserModel.findOne({ email }, function(err, user){
if(err) return res.status(500).send({ err });
if(!user) return res.status(501).send({ error: "Couldn't Find User"});
return res.status(200).send(user)
})
} catch (error) {
return res.status(404).send({ error: "Cannot find user data"})
}
}
Note:
- the email address exist in my mongoDB atlas i have checked it.
- I am using the GET method in postman
but my postman keeps showing me 404 error ‘cannot find user data’
what am i missing?
2
Answers
I guess you need to consider encoding the "@" symbol in the email address using percent-encoding like this:
However, I’ll suggest you pass the email as the body parameter instead of the params.
mongoose
is no longer support callback function infindOne()
. You can hold the data in a variable or use.then()
,.catch()
block.Here is the example of the solution of your code:
Here is some of things you have to consider,
await
keyword in your async function.findOne()
. Use{ "email": email }
instead of{ email }
I hope this helps!