Ada*_*m B 3 javascript arrays mongoose mongodb node.js
我正在构建的网站上有一个具有评论功能的页面。该网站就像露营地的 Yelp,并且 mongo 数据库集合中的每个露营地都有一个字段 - comments - 存储该露营地上发布的每条评论的 id,并且该 id 引用另一个名为 comments 的集合中的对象。添加、编辑、查看和删除评论均有效,但删除评论时除外,该评论的 id 不会从其关联营地的评论数组中删除。
以下是当前一个露营地的记录示例:
{
"_id" : ObjectId("5b18331953b9811c54ddc4cd"),
"contact" : {
"phone" : "403-748-4066",
"email" : "",
"website" : "https://www.albertaparks.ca/parks/central/aspen-beach-pp/information-facilities/camping/lakeview/"
},
"author" : {
"id" : ObjectId("5a998953342cbc7fe8521ef5"),
"username" : "Adam"
},
"createdAt" : ISODate("2018-06-06T19:04:25.418Z"),
"comments" : [
ObjectId("5b1bf59f8f21e152cce41b49")
],
"name" : "Lakeview",
"cost" : "40",
"location" : "Range Rd 284, Bentley, AB T0C 0J0, Canada",
"image" : "https://c1.staticflickr.com/9/8620/16612167676_6418f1b470_b.jpg",
"description" : "Open, pull-through sites are well-suited to RVs. There are unserviced, power, and power/water options. Trees provide some shade from the summer sun. There are many amenities available including a boat launch, playground, sewage disposal, flush toilets and showers. Camp along Gull Lake and enjoy swimming, boating, and the beach. Explore the trails and boardwalks for walking, biking, bird and wildlife watching. ",
"lat" : 52.4357744,
"__v" : 1,
"long" : -113.9873582
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,露营地对象当前引用了一条评论,但如果我要通过 UI 删除该评论,它将停止显示该评论,因为它将从评论集合中删除,但对露营地对象中的评论的引用将保持。这是我当前删除评论的代码:
app.delete("/campgrounds/:id/comments/:comment_id", middleware.checkCommentOwnership, function(req, res){
// RESTful - DESTROY
Comment.findByIdAndRemove(req.params.comment_id, function(err){
if(err){
req.flash("error", "Uh Oh! Something went wrong.");
res.redirect("/campgrounds");
}
Campground.findById(req.params.id, function(err, campground){
if(err){
req.flash("error", "Uh Oh! Something went wrong.");
res.redirect("/campgrounds");
}
campground.comments.remove(req.params.comment_id);
req.flash("success", "Comment has been deleted!");
res.redirect("back");
});
});
});
Run Code Online (Sandbox Code Playgroud)
然而该行
campground.comments.remove(req.params.comment_id);
Run Code Online (Sandbox Code Playgroud)
似乎不起作用。我也(粗略地)尝试过
campground.comments.remove("ObjectId(\"" + req.params.comment_id + "\")")
Run Code Online (Sandbox Code Playgroud)
尝试在注释数组中镜像 id 存储的格式,但这引发了此错误:
CastError: Cast to ObjectId failed for value "ObjectId("5b1bf4215f319752ab28ba49")" at path "comments"
Run Code Online (Sandbox Code Playgroud)
我主要使用 Mongoose 来与数据库交互。
抱歉,如果这是冗长的或重复的,我试图研究解决方案,但什么也没找到 - 至少没有我能理解的!
谢谢。
您需要使用 mongodb $pull运算符才能comment_id从数组中删除...
Campground.update({ _id: req.params.id }, { $pull: { comments: req.params.comment_id } }, function(err, campground){
if(err){
req.flash("error", "Uh Oh! Something went wrong.");
return res.redirect("/campgrounds");
}
req.flash("success", "Comment has been deleted!");
return res.redirect("back");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10006 次 |
| 最近记录: |