我通过在数组中推送错误消息来动态添加错误但是当我在函数中调用它时它不会执行任何操作。
router.post('/Registration',function(req,res){
var path = '/auth/Registration';
req.assert('username', 'Username is required').notEmpty();
req.assert('email', 'valid email required').notEmpty().isEmail();
req.assert('password', 'password is required').notEmpty();
req.assert('cpassword', 'password is required').notEmpty();
req.assert('phoneNumber', 'phone Number is required').isNumeric();
req.assert('age', 'age is required').notEmpty().isInt();
req.assert('designation', 'designation is required').notEmpty().isInt();
req.assert('timing', 'timing is required').notEmpty().notEmpty().isInt();
req.assert('sex', 'sex is required').notEmpty();
req.assert('joiningDate', 'joiningDate is required').notEmpty();
var errors = req.validationErrors();
if(errors) {
req.session.error = errors;
return res.redirect('/auth/Registration');
}
var errorsArr = [];
User.findOne({"username":req.body.username},function(err,user){
if(user){
errorsArr.push({"msg":"Username already been taken."});
}
User.findOne({"email":req.body.email},function(err1,user1){
if(user1) {
errorsArr.push({"msg":"Email already been taken."});
}
if(errorsArr.length > 0)
{
req.session.error = errorsArr;
return res.redirect('/auth/Registration');
}
});
});
var newUser = new User();
newUser.username = req.body.username;
newUser.password = req.body.password;
newUser.sex = req.body.sex;
newUser.email = req.body.email;
newUser.phoneNumber = req.body.phoneNumber;
newUser.age = req.body.age;
newUser.designation = req.body.designation;
newUser.timing = req.body.timing;
var CurrentDate = moment.tz(new Date(req.body.joiningDate),"Asia/Karachi").unix();
newUser.joiningDate = CurrentDate;
newUser.save(function(err,user){
if(!err)
return res.redirect('/auth/Login');
});
});
当我控制errorArray
时,它会显示一个空数组。
答案 0 :(得分:0)
您可以使用承诺 $ q 或简单地嵌套或回调来解决此问题。
简单的嵌套代码:
var errorsArr = [];
User.findOne({"username":req.body.username},function(err,user){
// you should check err
if(user){
errorsArr.push({"msg":"Username already been taken."});
}
User.findOne({"email":req.body.email},function(err1,user1){
// you should check err1
if(user1) {
errorsArr.push({"msg":"Email already been taken."});
}
console.log(errorsArr);
if(errorsArr.length > 0)
{
req.session.error = errorsArr;
return res.redirect('/auth/Registration');
}
});
});
答案 1 :(得分:0)
似乎findOne函数正在进行一些数据库查询。我在假设。如果是这样,它返回一个Promise,你不能这样处理它。 试试这个
User.findOne({"username":req.body.username}).then(function(user){
if(user){
errorsArr.push({"msg":"Username already been taken."});
}
}, function(err){
})