Reputation: 67
So I have the following document, its kind of a board the includes lists that includes tasks (like todo list)
{
"boardMembers": [
"5f636a5c0d6fa84be48cc19d",
],
"boardLists": [
{
"cards": [
{
"_id": "5f7c9b77eb751310a41319ab",
"text": "task one"
},
{
"_id": "5f7c9bb524dd8d42d469bba3",
"text": "task 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
}
How can I update and delete one of those cards? (I dont have a task schema, I want to delete the task from the board document
I tried this:
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 }],
}
);
res.send(board);
});
Upvotes: 1
Views: 146
Reputation: 3529
Use filtered positional operator $[<identifier>]
which identifies the array elements that match the arrayFilters
for updates.
For updating an object in cards
array:
Board.findOneAndUpdate(
{ _id: "boardId" },
{ $set: { "boardLists.$[outer].cards.$[inner].text": "update value" } },
{
arrayFilters: [
{ "outer._id": "boardListId" },
{ "inner.text": "task two" },
]
}
);
For removing an object in cards
array use $pull
Board.findOneAndUpdate(
{ _id: "boardId" },
{ $pull: { "boardLists.$[outer].cards": { text: "task two" } } },
{
arrayFilters: [{ "outer._id": "boardListId" }],
}
);
Upvotes: 1