节点js-如何从数组中删除特定的_id数据

时间:2018-11-26 07:15:59

标签: node.js mongodb express

这是我的删除功能route.js

router.delete("/qus/:id/answers/:answersId", function(req, res) {
        Forum.findOneAndUpdate({ _id: req.params.id }, {
                $pull: {
                    "answers" : { "answers._id": req.body.answersId }
                }
            }, { safe: true, multi: true },
            function(err,result) {
                if (err) {
                    console.log(err);
                    res.json({msg:"somethong went wrong"})
                }
                else {
                   res.json({msg:"success"});
                  // res.redirect("/qus/" + foundAnimal._id + "/answers");
                }
            });
    });

我的api外观

{
  "success": true,
  "forums": [
    {
      "createdAt": "2018-11-26T05:26:37.829Z",
      "likes": 0,
      "likedBy": [],
      "dislikes": 0,
      "dislikedBy": [],
      "_id": "5bfb84776cd9ea0ebc3db87b",
      "title": "how to apply visa",
      "body": "student visa requirement
      "qus_comments": [],
      "answers": [
        {
          "createdAt": "2018-11-26T06:59:21.840Z",
          "likesAnswer": 0,
          "likedAnswerBy": [],
          "dislikesAnswer": 0,
          "dislikedAnswerBy": [],
          "_id": "5bfb99eb21a1911650eba0d9",
          "content": "asdfghjk",
        },
        {
          "createdAt": "2018-11-26T06:59:21.840Z",
          "likesAnswer": 0,
          "likedAnswerBy": [],
          "dislikesAnswer": 0,
          "dislikedAnswerBy": [],
          "_id": "5bfb99f321a1911650eba0da",
          "content": "refersadfghj",
        }
      ],
      "__v": 13
    }
  ]
}

我的删除功能正在工作,此功能删除整个答案数组,但我想删除此答案数组中的任何特定ID。请帮我。我不知道该如何实施。如果有人知道,请帮助我。

1 个答案:

答案 0 :(得分:2)

在将answers._id用于给定的数据结构时,您需要直接使用$pull

Forum.findOneAndUpdate({_id: req.params.id}, {
  $pull: {"answers._id": req.body.answersId}
 },{ safe: true, multi: true },
 function(err,result) {
  if (err) {
      console.log(err);
      res.json({msg:"somethong went wrong"})
  }
  else {
     res.json({msg:"success"});
    // res.redirect("/qus/" + foundAnimal._id + "/answers");
 }
});

在某些情况下,可能是由于mongodb版本不同导致的,其工作原理如下:

Forum.findOneAndUpdate({_id: req.params.id}, {
  $pull: {"answers" : {"_id": req.body.answersId} }
});