如何解决猫鼬回调地狱承诺
由于模型之间的关系,我想将此回调切换为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,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");
}
});
}
});
});
试图尽我所能,但由于“无法读取null的属性'comments'”而导致错误
router.post("/",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
解决方法
您的数据库中似乎没有foundCampground
的记录。在推送到数组之前,请始终进行测试以查看是否从数据库返回了一条记录。如果没有特定查询的记录,findById
返回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();
if(foundCampground !== null){ //Added these line
foundCampground.comments.push(comment);
}
foundCampground.save();
})
.then(() => res.json("Comment added!"));
})
.catch((err) => {
res.json(`Error ${err}`);
});
});
,
答案
用猫鼬查询不是保证。为了将查询更改为Promise,必须使用 .exec()函数。
示例
router.post("/",res) => {
const text = req.body.text;
const newComment = new Comment({ text });
Campground.findById(req.params.id)
.exec() // This line makes the trick
.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}`);
});
});
参考
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。