Node.js检查用户是否已经存在
您好,我正在尝试检查数据库中是否已经存在用户,如果已经存在一个具有相同名称的用户,我设法停止创建该用户,但是我似乎没有得到显示的错误消息。我不太确定为什么我的错误没有得到正确处理。这是我的代码:
// Register User
router.post('/register', function(req, res){
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
//Validation
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
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.getUserByUsername(username, function(err, user){
if(err) throw err;
if(user){
return new Error('User already exists!');
}else{
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
}
});
req.flash('success_msg', 'You are registered and can now login');
res.redirect('/users/login');
}
});
回答如下:这将完全按照您的意愿运行。我在尝试使其正常运行时遇到了同样的问题,我向您保证。干杯!