【发布时间】:2020-12-24 11:08:14
【问题描述】:
我想将此回调切换为 Promise,但由于模型中的关系而遇到困难
router.post("/", middleware.isLoggedIn, (req, res) => {
Campground.findById(req.params.id, (err, campground) => {
if (err) {
console.log(err);
redirect("/campgrounds");
} else {
Comment.create(req.body.comment, (err, comment) => {
if (err) {
console.log(err);
} else {
comment.author.id = req.user._id;
comment.author.username = req.user.username;
comment.save();
campground.comments.push(comment);
campground.save();
res.redirect("/campgrounds/" + campground._id);
console.log("comment created");
}
});
}
});
});
尝试做我自己,但它出错了“无法读取属性 'cmets' of null”
router.post("/", (req, res) => {
const text = req.body.text;
const newComment = new Comment({ text });
Campground.findById(req.params.id)
.then((foundCampground) => {
newComment
.save()
.then((comment) => {
comment.author.id = req.user._id;
comment.author.username = req.user.username;
comment.save();
foundCampground.comments.push(comment);
foundCampground.save();
})
.then(() => res.json("Comment added!"));
})
.catch((err) => {
res.json(`Error ${err}`);
});
});
TIA
【问题讨论】:
标签: javascript node.js mongoose promise es6-promise