Skip to content
Advertisement

Handling Mongoose Query Errors in Express.js

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?

Advertisement

Answer

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"
        }
    })
})
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement