0

So let's say I want to make a Mongoose query to a database, inside of an Express post route:

app.post("/login",(req,res)=>{
    const username = req.body.username
    const password = req.body.password
    User.find({username:username},(err,user)=>{
        if (err) handleError(err)
        //if user exists
        if (user.length) {
            //check password
            if (user.password === password) {
                //assign jwt, redirect
            } else {
                //"username/password is incorrect"
            }
        } else {
            //"username/password is incorrect"
        }
    })
})

My concern is the handleError function. I'm not quite sure what kind of errors could even happen in Mongoose since it's just a simple query, but what should be included in the handleError function? And what response should I send to the user at that point?

2 Answers 2

2

You should in my opinion:

  • Use promises with async/await.
  • Don't catch any error(s) in your middleware and handle errors in the top-level express error handler. More on this here.
  • In your top-level express error handler, depending on the environment either return a simple message like: return res.status(500).json({ message: "Our server are unreachable for now, try again later." }); if this is in production. If you're in a local environment, return a JSON payload with the error in it like: return res.status(500).json({ err: <Error> });.

To sumerize, your code should look something like this:

app.post('/login', async (req, res) {
  
  // ES6 Destructuring
  const { username, password } = req.body;

  // Use findOne instead of find, it speeds up the query
  const user = await User.findOne({ username });

  if (!user || (user.password !== hashFunction(password))) {
    return res.status(403).json({ message: 'Bad credentials' });
  }

  // assign JWT and redirect
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can just send an error response with descriptive message related to Mongoose response.

app.post("/login",(req,res)=>{
    const username = req.body.username
    const password = req.body.password
    User.find({username:username},(error,user)=>{
        if (error){
          return res.status(400).json({message:"Can not perform find operation.", error: error });
        }
        //if user exists
        if (user.length) {
            //check password
            if (user.password === password) {
                //assign jwt, redirect
            } else {
                //"username/password is incorrect"
            }
        } else {
            //"username/password is incorrect"
        }
    })
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.