0

我对nodeJs有点陌生,我正在尝试检查用户的电子邮件是否已经存在于数据库中,但似乎我做错了什么,它总是告诉我“电子邮件已经存在”我尝试了几种不同的方法但没有他们工作。我希望这里有人能够帮助我解决这个问题。谢谢你。

router.post('/register', function (req, res) {
var name = req.body.name;
var email = req.body.email;
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();

req.checkBody('email', 'Email already exists').custom(email => {
    return User.getUserByEmail(email, function(user) {
        if (user) {
            throw new Error('this email is already in use');
        }
    })
});


// User.getUserByEmail(email, function (err, user) {
//
//     if(!isEmpty(user)){
//         console.log(user);
//         MyEmitter.emit('isUser', true);
//         var empty = '';
//         req.checkBody('empty', 'Username/Email is already taken').isEmpty();
//     }
// });
/** CKECK IF USER EXISTS  NEEDS TO BE WORKED ON */

var errors = req.validationErrors();

if (errors) {
    res.render('register', {
        errors: errors
    });
}else {
    var newUser = new User({
        name: name,
        email: email,
        username: username,
        password: password
    });
    User.createUser(newUser, function (err, user) {
        if (err) throw err;
    });

    req.flash('success_msg', 'Registration successful, please log in');
    res.redirect('/users/login');
}
 });

/** get user by email **/
module.exports.getUserByEmail = function(email, callback){
var query = {email: email};
User.findOne(query, callback);
}
4

1 回答 1

2

检查这个:

req.checkBody('email', 'Email already exists').custom(email => {
   User.findOne({email: email}).exec(function(user) {
       if (!user) {
           return true;
       }
       else{
           return false;
       }
    })
});
于 2018-07-01T11:36:14.737 回答