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

问题描述

用于Addtasks数组的Mongoose jSON代码格式:

{
    "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","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中您已经在Addtasks.$.Bigpaths的bigpaths数组中,因此您现在只需要指定用于搜索要删除的数据的键即可。

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