node.jsexpressmongooseconnect-flash

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

Solution

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