Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 为什么即使是';是否已成功保存到数据库中?_Mongodb_Express_Schema_Ejs - Fatal编程技术网

Mongodb 为什么即使是';是否已成功保存到数据库中?

Mongodb 为什么即使是';是否已成功保存到数据库中?,mongodb,express,schema,ejs,Mongodb,Express,Schema,Ejs,当我执行console.log(comments)时,它会打印注释的ID;当我执行console.log(post.comments.text)时,它会给出未定义的。但是,注释已成功保存在数据库中,并且 // COMMENT FUNCTION router.post("/:id/comments", middleware.isLoggedIn, function(req, res) { //look up for post using id Post.findByI

当我执行
console.log(comments)
时,它会打印注释的ID;当我执行
console.log(post.comments.text)
时,它会给出
未定义的
。但是,注释已成功保存在数据库中,并且

// 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.comments
是一个数组。数组没有
文本
字段,这就是它未定义的原因。如果要记录单个注释的文本,则需要按如下索引对其进行寻址:

console.log(post.comments[0].text);
for (let i = 0; i < post.comments.length; i++) {
  console.log(post.comments[i].text)
}
或者,您可以循环遍历数组中的所有注释,并按如下方式单独打印它们:

console.log(post.comments[0].text);
for (let i = 0; i < post.comments.length; i++) {
  console.log(post.comments[i].text)
}
for(设i=0;i
一种可能是在
post.save()
完成之前进行重定向,因此如果重定向请求很快进入,则新的post可能尚未提交到数据库。您可以为此编写代码,但在使用save上的completion回调完成
post.save()
之前,不能重定向。