0

Am I doing this correctly in the backend API? How would you delete an object inside an array within a parent array in the backend? I first found the main parent array index and then I found the object from tasks array using .tasks[index]. The question is how would I delete this in node? Tutorials I found uses req.params.id to delete an item but mine is more complicated.

    exports.deleteTaskItem = async (req, res) => {
      const taskindex = req.params.id;
      const index = req.params.index;
      try {
        const taskfound = await Task.findById(taskindex);
        const taskfounditem = await taskfound.tasks[index];
//code to type here
        res.status(204).json({
          status: "success",
          data: null
        });
      } catch (err) {
        res.status(404).json({
          status: "fail",
          message: err
        });
      }
    };

enter image description here

edelcodes
  • 67
  • 7

1 Answers1

0

I believe this piece of documentation would interest you: https://docs.mongodb.com/manual/reference/operator/update-array/

And to specify, I believe you want to use the $pull operator.

Something like this:

const {id, index} = req.params;
await Task.findByIdAndUpdate(id,{
    $pull: {
        tasks: { _id: index }
    }
});

(Disclaimer: I did not test this out this time, sorry. But it should be close.)

edit: Now when I reread the question I notice that you want to use the index. Personally I think it'd be easier to just add ids since you get that automatically if you use a sub-document. But if you insist on using index, maybe this answer can help:

https://stackoverflow.com/a/4970050/1497533

edit again: It seems this helped getting a working solution, so I'll copy it in from comments:

taskfound.tasks.splice(taskindex, 1); 
taskfound.markModified('tasks'); 
await taskfound.save();
ippi
  • 9,857
  • 2
  • 39
  • 50
  • Both taskfound and taskfounditem are returning the correct element in an array. I tried the following code but it didn't work: await Task.update( { _id: ObjectId(taskindex) }, { $pull: { tasks: [index] } } ); I also tried $pull: {tasks: index} but same result. – edelcodes Jul 31 '20 at 04:57
  • Well if you want to do it in more steps. `taskfound.tasks.splice(taskindex, 1); taskfound.markModified('tasks'); await taskfound.save();` – ippi Jul 31 '20 at 05:01
  • your solution worked! taskfound.tasks.splice(taskindex, 1); taskfound.markModified('tasks'); await taskfound.save(); Thank you so much. I love the people in this community and especially you ippi. – edelcodes Jul 31 '20 at 05:16