Search code examples
node.jsarraysexpressmongoosehandlebars.js

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


I have to update an element in array so I am pulling the value first and then pushing it with new data. I am trying this code and I am getting error in pull and push syntax.

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

Below is the Mongoose schema structure. I want to pull only the element 'status' in Addtasks array and push it with new one.

{
    "_id" : ObjectId("5f4217154a5a411a9473d64b"),
    "email" : "[email protected]",
    "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
}

Solution

  • I think you can simplify to one query using $set with the positional operator:

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

    This would update the first matching array element. If you want to update all elements use this operator:

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