如何等待猫鼬列表项被推送? [英] How to wait for mongoose list item to be pushed?

查看:59
本文介绍了如何等待猫鼬列表项被推送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Express路由,当用户单击以向线程提交新评论时会触发该路由.路由通过将新注释推送到猫鼬对象中列表的末尾,然后将用户重定向回他们来自的页面来处理此问题.这应该向他们显示所有评论的列表,包括他们刚刚添加的评论,但事实并非如此.而是显示未修改的列表.需要重新加载才能显示他们刚刚添加的评论.

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.

有问题的功能如下:

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?

推荐答案

将回调传递给report.save并从那里调用res.redirect:

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

这篇关于如何等待猫鼬列表项被推送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆