skip to Main Content

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:

  1. the email address exist in my mongoDB atlas i have checked it.
  2. 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


  1. I guess you need to consider encoding the "@" symbol in the email address using percent-encoding like this:

    GET: http://localhost:9000/api/user/success123%40gmail.com
    

    However, I’ll suggest you pass the email as the body parameter instead of the params.

    Login or Signup to reply.
  2. mongoose is no longer support callback function in findOne(). You can hold the data in a variable or use .then(), .catch() block.

    Here is the example of the solution of your code:

    export async function getUser(req, res) {
      const { email } = req.params;
        
      try {
        if (!email)
          return res.status(501).json({ error: "Invalid Username" })
        
        await UserModel.findOne({ "email": email })
          .then((docs) => {
            return res.status(201).json(docs)
          })
          .catch((err) => {
            return res.status(501).json(err)
          });
      } catch (error) {
        return res.status(404).send({ error: "Cannot find user data" })
      }
    }
    

    Here is some of things you have to consider,

    1. Don’t forget to use the await keyword in your async function.
    2. Try to write the code in Ecmascript
    3. Use key-value pair in findOne(). Use { "email": email } instead of { email }

    I hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search