如何使用nodejs删除猫鼬对象数组中的特定元素?

How to remove the specific element in an array of objects in mongoose using nodejs?

我必须更新数组中的一个元素,所以我先提取值,然后用新数据推送它。 我正在尝试这段代码,但在拉和推语法中遇到错误。

  User.findOneAndUpdate({email:req.user.email}, {$pull: {Addtasks.status : {commonID:req.query.commonIDs}}},
    function (error, success) {
          if (error) {
              console.log(error);
          } else {
            User.findOneAndUpdate({email:req.user.email}, {$push: {Addtasks.status: req.query.selectedValue}},
            function (error, success) {
                  if (error) {
                    console.log("Something wrong when updating data!");
                  } else {
                    res.redirect('/taskswriter');
                      console.log("success");
                    }
            });
            }
    });

下面是 Mongoose 模式结构。我只想拉出 Addtasks 数组中的元素 'status' 并用新元素推送它。

{
    "_id" : ObjectId("5f4217154a5a411a9473d64b"),
    "email" : "charlotte@grumpytext.com",
    "name" : "Charlotte Miles",
    "Addtasks" : [ 
        {
            "commonID" : "66k4xorn77x",
            "status" : "Requirement Completed",
            "Date" : "Sun Aug 23 2020 12:43:57 GMT+0530 (India Standard Time)",
            "exampleRadios" : "option1",
            "otherdetails" : "bnbn",
            "website" : "asad.com",
            "keywords" : "anxiety disorders for children, anxiety disorders for adults",
            "words" : 12345,
            "topic" : "How article is generated?",
            "_id" : ObjectId("5f4217354a5a411a9473d64d")
        }, 
        {
            "commonID" : "offo357aak",
            "status" : "Requirement Completed",
            "Date" : "Sun Aug 23 2020 12:44:20 GMT+0530 (India Standard Time)",
            "exampleRadios" : "option1",
            "otherdetails" : "trhr",
            "website" : "dsfdd.com",
            "keywords" : "Kali from Kaliyug, Kaliki Vishnu Avatar, Vishnu's 10th Avatar",
            "words" : 5678,
            "topic" : "When the Kaliyug era will end ?",
            "_id" : ObjectId("5f42174c4a5a411a9473d651")
        }
    ],
    "__v" : 0
}

我认为您可以使用 $set 和位置 operator:

简化为一个查询
User.findOneAndUpdate({email:req.user.email}, 
                      { $set: { "Addtasks.$" : req.query.selectedValue } })

这将更新第一个匹配的数组元素。如果要更新所有元素,请使用 this operator:

User.findOneAndUpdate({email:req.user.email}, 
                      { $set: { "Addtasks.$[]" : req.query.selectedValue } })