Can someone please help me create a mongoose query to delete a task in a tasks array when nested like the following todolist model

const TodoSchema = new mongoose.Schema({
  user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "users",
  },
  categories: [
    {
      id: {
        type: mongoose.Schema.Types.ObjectId,
      },
      category: {
        type: String,
      },
      tasks: [
        {
          id: {
            type: mongoose.Schema.Types.ObjectId,
          },
          task: {
            type: String,
          },
          done: {
            type: Boolean,
          },
        },
      ],
    },
  ],
});

I’ve tried several different onces, the closest I’ve gotten is the following:

const deletedTask = await Todos.updateOne(
    { user_id },
    {
      $pull: {
        categories: {
          tasks: {
            _id: taskToDelete,
          },
        },
      },
    }
  );

I someone can help me delete a certain task in the array I would highly appreciate it.

I figured the axios query after dealing with it for 4-5 hours. For anyone else going through noSQL queries and updated, I feel you, here’s the solution with a delete request on the server side for the above pointed model:

router.delete("/:user_id/:category_id/:id", async (req, res) => {
  // Define the user_id and category_id and prep them for the DB query
  const user_id = mongoose.Types.ObjectId(req.params.user_id);
  const taskToDelete = mongoose.Types.ObjectId(req.params.id);

  // Finding the user's todo list object
  const userTodoList = await Todos.findOne({ user_id });

  // Finding the index of the category where the task is located
  const categoryIndex = userTodoList.categories.findIndex(
    (curr) => curr._id.valueOf() === req.params.category_id
  );

  // Concatenate the key before the query, so there's no errors when creating it
  const keyValue = "categories." + categoryIndex + ".tasks";

  // Query and pull out the task by its id
  const deletedTaskConf = await Todos.updateOne(
    { user_id },
    {
      $pull: {
        [keyValue]: {
          _id: taskToDelete,
        },
      },
    }
  );

  res.send(deletedTaskConf );
});

Since for some reason you can not pass the category index as a single digit number through params, I took the category_id and did another query to find its index and used it to make the key in the key: value to find the task array and $pull the task id that needed to get pulled out, hope this helps someone dealing wth the same nested arrays in objects and trying to navigate this. Let me know if this helped anyone, and also if you have a better solution please let me know, so the category index query can be remove if possible.

1 Like