如何使用 nodejs 在 mongoose 中拉取或删除另一个数组中的数组元素?

How to pull or delete array's element inside another array in mongoose using nodejs?

猫鼬 jSON Addtasks 数组的代码格式:

{
    "Id4AddtasksBigpaths" : "6cbt51fho5y$s",
    "clientName" : "Vikas Yadav",
    "deadline" : "Set Deadline",
    "assignee" : "Assign",
    "displayLock" : "inline",
    "displayDelete" : "none",
    "commonID" : "s6gf40ca5rq",
    "status" : "Requirement Completed",
    "Date" : "Thu Sep 17 2020 18:12:23 GMT+0530 (India Standard Time)",
    "exampleRadios" : "option1",
    "otherdetails" : "trhr",
    "website" : "dsfdd.com",
    "keywords" : "customer values, revenue targets",
    "words" : 33252,
    "topic" : "What is a problem that your target customer has?",
    "_id" : ObjectId("5f6359af8c5ed924b84fdf71"),
    "Bigpaths4Clients" : [],
    "Bigpaths" : [ 
        {
            "path" : "public\files\Best VR Headset.docx",
            "name" : "Best VR Headset.docx",
            "Id4AddtasksBigpaths" : "6cbt51fho5y$s",
            "uniqueId" : "ztojaap0hoqu$id"
        }, 
        {
            "path" : "public\files\chsl_marks2018.pdf",
            "name" : "chsl_marks2018.pdf",
            "Id4AddtasksBigpaths" : "6cbt51fho5y$s",
            "uniqueId" : "gbgz1z404hu$id"
        }
    ]
}

代码如下: 我正在尝试使用以下代码来执行此操作但无法正常工作。 我想根据路由中传递的参数 id 删除 Bigpaths 数组中的特定对象。我哪里错了?

router.get('/profile/view/removeThumbnail/:id/:uniqueId', function(req, res, next) {
console.log(req.params.id);
console.log(req.params.uniqueId);

  User.updateMany({"Addtasks.Id4AddtasksBigpaths":req.params.id}, {$pull: {"Addtasks.$.Bigpaths" : {"Bigpaths.$.uniqueId": req.params.uniqueId}}},
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
          // res.render('viewTask');
            console.log('path removed succesfully');
          }
});
})

您的查询有误。在这里,我为您修复了它。由于在 $pull 中您已经在此处的 bigpaths 数组中 Addtasks.$.Bigpaths 您现在只需要指定键来搜索要删除的数据。

User.updateMany({
     "Addtasks.Id4AddtasksBigpaths": req.params.id
 },
 {
     $pull: {
         "Addtasks.$.Bigpaths": {
             "uniqueId": req.params.uniqueId
          }
     }
  })