在mongodb上存储数据之前需要检查用户名和电子邮件是否存在

b1zrtrql  于 2023-06-29  发布在  Go
关注(0)|答案(3)|浏览(165)
User.find({username : username}, function (err, docs){
    if (docs.length){
         console.log(docs.length);
    }else{
         console.log('Insert');
    }
});

现在我可以检查用户名,但不能在两个。我的查询是用户名或电子邮件,如果存在,则显示用户名存在或电子邮件存在的消息。我有一个工作函数用于存储数据到db

oug3syen

oug3syen1#

User.find({$or: [{email: email},{username: username}]}, function (err, docs) {
            if (docs.length!=0){
                //console.log(req.body.email);
                // Check record has same username as you are using in find
                if(docs[0].username == username){
                    //console.log(docs[0].email);
                    //console.log(docs[0].username);
                    //console.log(docs[0].username+'__'+username);
                    console.log("username Already exist");
                }
                // Else Check record has same email as you are using in find
                else if(docs[0].email == email){
                    console.log("Email Already exist");
                }
            }else{
                console.log('Insert');
            }

});

只有一个问题,在这两种情况下,它都返回第一个条件,即“用户名已被占用”。

eqqqjvef

eqqqjvef2#

尝试$or操作符。

User.find({$or: [
        {email: req.body.email},
        {username: req.body.username}
    ]}, function(err, docs) {
        //do anything
        //if(email) is matched{ console.log("Email already taken ");}
        //else if(username) is matched{ console.log("Username already taken")}
        else{
            //call Update function
        }
    });
bkhjykvo

bkhjykvo3#

对于Mongoose版本7以后,你不能使用回调,因此一个解决方案是使用.then()方法,如下所示:

User.find({ $or: [{ username: req.body.username },{ email: req.body.email} ],}).then(result) => {
//since the result is an array of objects you should get the first element of it in order to have access to the username/email property
//to prevent any errors if there is no users found make sure to use the optional chaining operator '?.'
  if(result[0]?.username === username) {
    return res.status(400).json({message: "Username is already in use!"}) 
  } else if {result[0]?.email === email) {
    return res.status(400).json({message: "Email is already in use!"}) 
  } 
}

相关问题