简体   繁体   中英

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?

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
});

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"
        }
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM