javascript - Node/ Mongoose - 从数组中删除 ObjectId

标签 javascript arrays node.js mongodb mongoose

<分区>

我正在构建的网站上有一个页面具有评论功能。该网站就像露营地的 Yelp,mongo 数据库中集合中的每个露营地都有一个字段 - 评论 - 存储在该露营地发布的每条评论的 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 
}

如您所见,campsite 对象当前引用了一条评论,但如果我要通过 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");
        });
    });
});

不过行

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

好像不行。我也(粗略地)尝试过

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

尝试在评论数组中反射(reflect) ID 存储的格式,但这会引发此错误:

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

我主要使用 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");
});

关于javascript - Node/ Mongoose - 从数组中删除 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50776078/

相关文章:

javascript - 减少 promise 提前返回

javascript - js 冒泡排序未正确处理所有元素

javascript - 更改 Javascript 来更新面板

c++ - 指向二维数组的指针

java - 交换元素

node.js - react native : Failed to construct transformer: Error: Cannot create a string longer than 0x1fffffe8 characters

javascript - 为什么事件监听器点击需要返回函数才能工作

javascript - 电话间隙签名抽奖

arrays - 如何在 golang 中将字节数组打印为二进制?

node.js - ReactJS 与 azure SAML SSO 集成