skip to Main Content

I want to delete the object where the name is "Sleep".
The code I am using:

const listName = "Holiday;
  const item = new Item({
    name: "Sleep"
  });
  User.updateOne({username : req.user.username}, {$pull:{"lists.$[updateList].items" : item}}, {
    "arrayFilters": [
      {"updateList.name" : listName}
    ]
  }).exec().then(function(){
    console.log("Deleted successfully");
    res.redirect("/list-"+listName);
  })

The mongodb object:

  "_id" : ObjectId("64797ebc9e84ed9d8be3ea54"),
  "username" : "[email protected]",
  "lists" : [
      {
          "name" : "Holiday",
          "items" : [
              {
                  "name" : "Welcome to your todo-list!",
                  "_id" : ObjectId("647988267f3ddfc2982f7d77")
              },
              {
                  "name" : "Click + to add another item.",
                  "_id" : ObjectId("647988267f3ddfc2982f7d78")
              },
              {
                  "name" : "<-- Click this to delete an item.",
                  "_id" : ObjectId("647988267f3ddfc2982f7d79")
              },
              {
                  "name" : "Sleep",
                  "_id" : ObjectId("64799279c3da415dc4ce7574")
              },
              {
                  "name" : "WakeUp",
                  "_id" : ObjectId("6479930e6d49e494aad1dffa")
              }
          ],
          "_id" : ObjectId("647988357f3ddfc2982f7d85")
      }
]
}

It seems there is some problem with the updateOne and $pull: attributes but I can’t figure out what.

2

Answers


  1. Try with

    const listName = 'Holiday';
    User.updateOne(
      { username: req.user.username, 'lists.name': listName },
      { $pull: { 'lists.$[].items': { name: 'Sleep ' } } }
    )
      .exec()
      .then(function () {
        console.log('Deleted successfully');
        res.redirect('/list-' + listName);
      });
    
    Login or Signup to reply.
  2. I have tested this code, it’s working fine.

    Note: just write object id in findOne({_id}) function. No need to edit
    it. Use this code inside asyn function

    const user = await user.findOnde({_id:_id /*give object id here-- 
        commented*/});
     const user_lists= user.lists
     const deleted_item_name="Sleep"; // Change it, if you want to delete other then "Sleep" named items.
     let new_lists=[];
     let new_items=[];
         user_lists.forEach((obj,index)=>{
               
          new_items= obj.items.filter((inner_obj,i)=>{
               
            if(inner_obj.name!=deleted_item_name)
            {
              return inner_obj;
            }
          })
          new_lists.push({name:obj.name,items:new_items})
    
         })
    
         user.lists= new_lists;
         await user.save();
         res.status(200).json(new_lists);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search