【问题标题】:How to pull or delete array's element inside another array in mongoose using nodejs?如何使用nodejs在mongoose的另一个数组中拉取或删除数组的元素?
【发布时间】:2020-09-17 21:51:04
【问题描述】:

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",
            "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');
          }
});
})

【问题讨论】:

  • 虽然控制台显示消息:'路径已成功删除'但实际上它仍然存在。

标签: node.js arrays mongoose handlebars.js pull-request


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    相关资源
    最近更新 更多