0

I have an Express route that is triggered when a user clicks to submit a new comment to a thread. The route handles this by pushing the new comment to the end of a list in a mongoose object and then redirecting the user back to the page they came from. This should show them a list of all the comments, including the one they just added, but it doesn't. Instead it shows the unmodified list. A reload is needed to show the comment they just added.

The function in question is as follows:

router.post('/get/:faultId/new_comment', function(req, res, next) {
  var commenter = req.body.first_name + " " + req.body.last_name;
  var comment = req.body.new_comment_text
  var datetime = Date.now();

  var comment_object = commentCreate(commenter, comment, datetime);

  FaultReport
    .findOne({
      '_id': req.params.faultId
    })
    .exec(function(err, report) {
      if (err) return console.error(err);
      report.comment.push(comment_object);
      report.save();
    });

  res.redirect('/api/get/' + req.params.faultId);
});

I'm clearly misunderstanding something. How can I wait for the database to be updated before redirecting the user?

smolloy
  • 308
  • 1
  • 11

1 Answers1

0

Pass a callback to report.save and call res.redirect from there:

router.post('/get/:faultId/new_comment', function(req, res, next) {
  var commenter = req.body.first_name + " " + req.body.last_name;
  var comment = req.body.new_comment_text
  var datetime = Date.now();

  var comment_object = commentCreate(commenter, comment, datetime);

  FaultReport
    .findOne({
      '_id': req.params.faultId
    })
    .exec(function(err, report) {
      if (err) return console.error(err);
      report.comment.push(comment_object);
      report.save(function(err) {
        res.redirect('/api/get/' + req.params.faultId);
      });
    });
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471