Node / Mongoose - 从数组

时间:2018-06-09 16:00:10

标签: javascript arrays node.js mongodb mongoose

我在我正在构建的网站上有一个页面,其中包含评论功能。该网站就像营地的Yelp一样,mongo db中的每个营地都有一个字段 - 评论 - 存储该营地上发布的每条评论的ID,id指的是另一个名为评论的集合中的对象。除了删除评论之外,添加,编辑,查看和删除评论都是有用的,该评论的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 
}

正如您所看到的露营地对象目前引用了一条评论,但如果我要通过用户界面删除评论,它将停止显示评论,因为它将从评论集合中删除但是对评论的引用露营地对象将保留。这是我目前删除评论的代码:

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");
        });
    });
});

但行

campground.comments.remove(req.params.comment_id); 

似乎不起作用。我也(粗略地)尝试了

campground.comments.remove("ObjectId(\"" + req.params.comment_id + "\")")

尝试镜像存储id的格式,在comments数组中但是这引发了这个错误:

CastError: Cast to ObjectId failed for value "ObjectId("5b1bf4215f319752ab28ba49")" at path "comments"

我主要使用Mongoose与db进行交互。

对不起,如果这是漫长的啰嗦或重复,我试着研究解决方案但却找不到任何东西 - 至少没有什么是我能理解的!

感谢。

2 个答案:

答案 0 :(得分:1)

尝试从数组中删除,标记为已更改并保存,如此

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.filter(comment => comment.toString() === 
                req.params.comment_id);
            campground.markModified('comments');
            campground.save(function(err){
            if(err){
                 req.flash("error", "Uh Oh! Something went wrong.");
                 res.redirect("/campgrounds");
                 return;
            }
            req.flash("success", "Comment has been deleted!");
            res.redirect("back");
                })
        });
    });
});

答案 1 :(得分:1)

您需要使用mongodb here运算符才能从数组中删除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"); }); ...

def work_block():
    # stop print "Hello" from executing
    global print_text
    print_text = lambda : None