简体   繁体   中英

custom field validation and error handling in nodejs and express

I am trying to add a username field upon registration, I already did validation using express-validator to make sure it's not empty since I want everyone to have their unique username.The same way we checked if user exist using email, i would like to check using username as well... please check my code below

Any idea how I can display the error for username, separately from the error of email already exist?

try {
  let user = await User.find({
    'email': email,
    'username': username
  })

  //Check if user exists
  if (user) {
    res.status(400).json({
      errors: [{
        msg: 'user with that name or username already exist'
      }]
    })
  }

You should use findOne (it returns null if document doesn't exists) instead as find returns and array so

if(user)

will always be true,Something like below

try {
        let user = await User.findOne({ 'email': email, 'username': username })

    //Check if user exists
        if (!user) { 
           res.status(400).json({
                errors: [{ msg: 'user with that name or username already exist' }]
            })
        }


}

Moreover your query will look for the combination of email and username,ie where both username or email provided by you exists

What you can do is use $or operator

try {
    let user = await User.findOne({
        $or: [{
            'email': email
        }, {
            'username': username
        }]
    })

    //Check if user exists
    if (!user) {
        res.json({
            error: "Both email and username doesn't exist"
        })

    } else if (user) {
        if (user.email != email) {

            res.json({
                error: "Email Doesn't exists"
            })
        } else if (user.username != username) {
            res.json({
                error: "Username Doesn't exists"
            })
        }
       else  {
            res.json({
                error: "Both Username and Email  exists"
            })
        }

    }


}

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