【问题标题】:Why comments are not showing even though it's successfully saved on database?为什么即使成功保存在数据库中,评论也没有显示?
【发布时间】:2020-09-07 17:40:14
【问题描述】:

当我执行 console.log(comments) 时,它会打印 cmets 的 ID,当我执行 console.log(post.comments.text) 时,它会给出 undefined。但是,cmet 成功保存在数据库中,并且

// COMMENT FUNCTION

router.post("/:id/comments", middleware.isLoggedIn, function(req, res) {
  //look up for post using id
  Post.findById(req.params.id, function(err, post) {
    if (err) {
      console.log(err);
      req.flash("error", "something went wrong")
      res.redirect("/posts");
    } else {
      //Create comment
      req.body.comment.body = req.sanitize(req.body.comment.body);

      Comment.create(req.body.comment, function(err, comment) {
        if (err) {
          console.log(err);
          req.flash("error", "OOPS! something went wronng")
        } else {
          //add username and id to comment
          comment.author.id = req.user._id;
          comment.author.username = req.user.username;
          comment.save();
          post.comments.push(comment);
          post.save();
          console.log(post.comments.text);

          req.flash("success", "Comment added successfully");

          res.redirect("/posts/" + post._id);
          //console.log("comment is saved");
        }
      });
    }
  });
});

【问题讨论】:

  • 一种可能性是您在post.save() 完成之前重定向,因此如果该重定向请求很快进入,新帖子可能尚未提交到数据库。您可以为此编写代码,但在 post.save() 完成之前不要重定向,方法是在保存时使用完成回调。

标签: mongodb express schema ejs


【解决方案1】:

post.comments 是一个数组。数组没有 text 字段,这就是它未定义的原因。如果您想记录单个评论的文本,您需要通过索引来解决它,如下所示:

console.log(post.comments[0].text);

或者您可以遍历数组中的所有 cmets 并像这样单独打印它们:

for (let i = 0; i < post.comments.length; i++) {
  console.log(post.comments[i].text)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多