首页 > 解决方案 > 如何使用expressjs在mongoDB的嵌套数组中只删除一个对象元素?

问题描述

我正在尝试以下代码来删除评论。所以我想要的是,每当我点击删除相应评论时,它都应该被删除。但是我在这里面临的问题是,无论单击任何删除按钮,它都会删除所有评论。为什么会这样?

删除评论的路由代码。

router.route("/deleteComment").get(function(req, res) {
  console.log("AddtasksId = "+req.query.AddtasksId + "id = "+req.query.id);
  Comments.findOneAndUpdate({'AddtasksMain.AddtasksId':req.query.AddtasksId},
  {$pull: {"AddtasksMain.$.comments":{"_id": req.query.id}}},
  function(err, deleteComments) {
    if(deleteComments) {
      console.log("Comment deleted!")
      return res.end('{"msg" : "Comment Deleted", "status" : 200}');
       }
      else {
      return res.end('{"msg" : "Comment not Deleted", "status" : 300}');
      }
  });
});

AJAX 调用:

$(document).on("click", ".deleteComments", function() {    
    var id = $(this).prop("id");
    var AddtasksId = $('#submitBtn4comment').attr('data-taskId');
  $.ajax({
    type: "GET",
    url: "/deleteComment",
    dataType: "json",
    data: {
      AddtasksId: AddtasksId,
      id:id
    },
    contentType: "application/json",
    success: function(response){
    if(response.status == 200)
    window.location.reload();
  }
  });
})

评论架构:

{
    "AddtasksId" : "cxlq2iqy85qy$s",
    "_id" : ObjectId("5fcd1ca940542e29c0b4b0c7"),
    "comments" : [ 
        {
            "commentDate" : "Dec 7 2020 at 0:14",
            "comment" : "Closing it now.",
            "username" : "Michael Con",
            "_id" : ObjectId("5fcd268e40542e29c0b4b0d9")
        },
       {
            "commentDate" : "Dec 9 2020 at 0:14",
            "comment" : "Close it now.",
            "username" : "Ricky K",
            "_id" : ObjectId("5fcd268e40586e29c1b4b0r7")
        }
    ]
}

我只想通过_id:5fcd268e40586e29c1b4b0r7 单击删除锚文本来删除假设只有第二条评论。但不是删除一条评论,而是删除所有评论。请告诉我发生了什么事?

更新:

var commentSchema = new mongoose.Schema({

ClientId: {
    type: String,
    unique: true
  },

  AddtasksMain : [{
    AddtasksId: String,
    comments: [
      {
      username: String,
      comment: String,
      commentDate:String
    }
   ]
 }]

});

标签: node.jsajaxmongoosehandlebars.jscomments

解决方案


我只是将其更改findOneUpdateOneUpdateMany并且有效。这是解决方案UpdateMany

router.route("/deleteComment").get(function(req, res) {
  console.log("AddtasksId = "+req.query.AddtasksId + "id = "+req.query.id);
  Comments.updateMany({'AddtasksMain.AddtasksId':req.query.AddtasksId},
  {$pull: {"AddtasksMain.$.comments":{"_id": req.query.id}}},
  function(err, deleteComments) {
    if(deleteComments) {
      console.log("Comment deleted!")
      return res.end('{"msg" : "Comment Deleted", "status" : 200}');
       }
      else {
      return res.end('{"msg" : "Comment not Deleted", "status" : 300}');
      }
  });
});

推荐阅读