【发布时间】: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