Hitesh Chavda
Hitesh Chavda

Reputation: 789

Express js res.redirect() from mongoose callback not working

What I'm trying to do here is,

from /expense/new page submitting POST request to /expense/newPost

on Expressjs, handling this way

app.post('/expense/newPost', function(req, res) { ...

continue, using mongoose I validate the collection as

tmpExp = new Expense(req.body);

tmpExp.validate(function(err) {
  if(err || !isValidForm) {
    req.session.form.errField =  _.extend(req.session.form.errField, (err.errors || err ));
    req.session.rePop = req.body;
    res.redirect('/expense/new');
  } else {
    console.log('now saving') // successfully logs here.
    tmpExp.save(expPost, function(err2, savedDoc) {
      if(err2) {
        req.session.flash = { 
            global: true
          , css: "error"
          , message: "Internal Server Error"
        }
        res.redirect('/expense/new');
      } else {
        res.redirect('/expense/new?success=' + savedDoc.bill_id);
      }
    });
  }
});

for shake of clearity I removed some of the validation code.

Now the problem is, after submitting the POST request by browser data is successfully saved in mongodb but browser not redirect and just waiting for response from server

Upvotes: 0

Views: 3605

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161457

Your save callback is not passed in properly.

tmpExp.save(expPost, function(err2, savedDoc) {

should be:

tmpExp.save(function(err2, savedDoc) {

Upvotes: 3

Aurelia
Aurelia

Reputation: 1062

Assuming verification code is the only thing you stripped from this file, res is not defined. I'd suggest you just return Error or null and do the remaining logic in the parent function, where res is likely to be present. This also is generally a good practice because your model will be reusable (no path parts in the model)

Upvotes: 1

Related Questions