Timo222
Timo222

Reputation: 67

How to update and delete item from array in mongoose?

I have a board object and I want to edit it from express and mongoose, this is my object:

"boardMembers": [
        "5f636a5c0d6fa84be48cc19d",
    ],
    "boardLists": [
        {
            "cards": [
                {
                    "_id": "5f7c9b77eb751310a41319ab",
                    "text": "card one"
                },
                {
                    "_id": "5f7c9bb524dd8d42d469bba3",
                    "text": "card two"
                }
            ],
            "_id": "5f7c9b6b02c19f21a493cb7d",
            "title": "list one",
            "__v": 0
        }
    ],
    "_id": "5f63877177beba2e3c15d159",
    "boardName": "board1",
    "boardPassword": "123456",
    "boardCreator": "5f636a5c0d6fa84be48cc19d",
    "g_createdAt": "2020-09-17T15:57:37.616Z",
    "__v": 46
}

Now this is my code, I tried to do it with $pull, but nothing happend when I check it on Postman

router.put("/delete-task/:list/:task", auth, boardAuth, async (req, res) => {
  const listId = req.params.list;
  const task = req.params.task;

  const board = await Board.findOne({ _id: req.board._id });
  if (!board) return res.status(404).send("no such board");

  Board.findOneAndUpdate(
    { _id: req.board._id },
    { $pull: { "boardLists.$[outer].cards": { _id: task } } },
    {
      arrayFilters: [{ "outer._id": listId }],
    }
  );
  await board.save();
  res.send(board);
});

what I am missing here?

Upvotes: 0

Views: 1097

Answers (1)

Shivam Verma
Shivam Verma

Reputation: 957

Hope this will work in your case, you just need to convert your ids into mongo objectId. So your code will look something like this:

import mongoose from "mongoose";

const task = mongoose.Types.ObjectId(req.params.task);
const listId = mongoose.Types.ObjectId(req.params.list);

board = await Board.findOneAndUpdate(
    { _id: req.board._id},
    { $pull: {
           "boardLists.$[outer].cards": { _id: task }
        }
    },
    {
      arrayFilters: [{ "outer._id": listId }],
      returnNewDocument: true
    }
);

res.send(board);

Upvotes: 1

Related Questions