通过快速验证器验证用户

时间:2018-07-01 09:13:49

标签: node.js express express-validator

我对nodeJ还是陌生的,我正在尝试检查数据库中是否已经存在用户的电子邮件,但是好像我做错了什么,它总是告诉我“电子邮件已经存在”,我尝试了一些尝试方式,但都不起作用。我希望这里有人能够帮助我解决这个问题。谢谢。

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

1 个答案:

答案 0 :(得分:0)

选中此一项:

req.checkBody('email', 'Email already exists').custom(email => {
   User.findOne({email: email}).exec(function(user) {
       if (!user) {
           return true;
       }
       else{
           return false;
       }
    })
});