0

I have no clue how can I push an object to a nested array

this is the Board document:

{
    "boardMembers": [
        "5f636a5c0d6fa84be48cc19d"
    ],
    "boardLists": [
        {
            "cards": [],
            "_id": "5f6387e077beba2e3c15d15a",
            "title": "list one",
            "__v": 0
        }
    ],
    "_id": "5f63877177beba2e3c15d159",
    "boardName": "board1",
    "boardPassword": "123456",
    "boardCreator": "5f636a5c0d6fa84be48cc19d",
    "g_createdAt": "2020-09-17T15:57:37.616Z",
    "__v": 2
}

I need to push a task inside the cards array (to a specific list with ID)

here is the code:

outer.post("/add-task/:id", auth, boardAuth, async (req, res) => {
  const listId = req.params.id;

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

    const list = await List.findOne({ _id: listId });
    if (!list) return res.status(404).send("List not found");

    const task = new Task({
      text: req.body.text,
    });

    board.boardLists.map((list) => {
      if (listId.toString() === list._id.toString()) {
        list.cards.push(task);
      } else {
        console.log("no task");
      }
    });

    await board.save();
    res.send(board);
});

now the problem is when I make the request in postman its shows me the task inside the cards array i want but its not saving it to the mongoDB

1 Answer 1

2

You're using array.map() but:

  1. Nothing is returned in the callback of map(), which will return an array with each element undefined;
  2. You aren't assigning the array returned by map() to anything.

So, you can use array.map() to return an array in which the task is pushed to the desired list in board.boardLists like so:

board.boardLists = board.boardLists.map((list) => {
  if (listId.toString() === list._id.toString()) {
    return {
      ...list,
      cards: list.cards.concat(task)
    }
  } else {
    return list
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

just add a " , " after ...list and try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.