简体   繁体   English

nodejs 和 express 中的自定义字段验证和错误处理

[英]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我正在尝试在注册时添加用户名字段,我已经使用 express-validator 进行了验证,以确保它不为空,因为我希望每个人都有自己唯一的用户名。就像我们使用 email 检查用户是否存在一样,我想检查使用用户名...请检查下面的代码

Any idea how I can display the error for username, separately from the error of email already exist?知道如何显示用户名的错误,与 email 的错误分开吗?

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您应该使用findOne (如果文档不存在,它会返回null )而不是find返回和数组所以

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此外,您的查询将查找 email 和用户名的组合,即您提供的用户名或 email 都存在

What you can do is use $or operator您可以做的是使用$or运算符

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

    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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