kogik
kogik

Reputation: 3

How can I call req.flash() from inside the mongoose?

I have a problem calling req.flash inside mongoose function. I have tried lit everything. In one part of my code it works but in other it doesn't.

My code:

 router.post('/chngpwd', function(req, res, next) {
   var {currentpassword, newpassword, confirmnewpassword} = req.body;
   var uid = req.session.passport.user;
   if (newpassword == confirmnewpassword) {
     User.findById(uid).then(dbres => {
     req.flash('error_msg',"THIS MESSAGE DON'T WORK");  //DONT WORK
     });
   }else {
     req.flash('error_msg',"New passwords don't match"); //WORKS
   }
   res.redirect('/adminpanel/1');
});

Upvotes: 0

Views: 245

Answers (1)

Nipun Chawla
Nipun Chawla

Reputation: 366

You are redirecting it to /adminpanel/1 without waiting the response from the findById (async) function. This should work:

router.post('/chngpwd', function(req, res, next) {
   var {currentpassword, newpassword, confirmnewpassword} = req.body;
   var uid = req.session.passport.user;
   if (newpassword == confirmnewpassword) {
     User.findById(uid).then(dbres => {
         req.flash('error_msg',"THIS MESSAGE DON'T WORK");
         res.redirect('/adminpanel/1');
     });
   }else {
     req.flash('error_msg',"New passwords don't match");
     res.redirect('/adminpanel/1');
   }
});

Upvotes: 1

Related Questions