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');
}
});
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!"})
}
}
3条答案
按热度按时间oug3syen1#
只有一个问题,在这两种情况下,它都返回第一个条件,即“用户名已被占用”。
eqqqjvef2#
尝试
$or
操作符。bkhjykvo3#
对于Mongoose版本7以后,你不能使用回调,因此一个解决方案是使用.then()方法,如下所示: