0

I have the following Board object:

{
    "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
}

as you can see there is a "boardLists" array, I want to make a post request that post a card to a list inside that array with specific ID.

that my code:

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

  try {
    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.updateOne(
      { _id: req.board._id, "boardLists._id": listId },
      { $push: { "boardLists.$.cards": task } }
    );

    await board.save();
    res.send(board);
  } catch (err) {
    console.log(err);
  }
});

Now the problem is when I make the request call in postman its does the push inside the specific list that i want but its not saving the push inside the parent board object: when do a get request to that object i get an empty cards array. like that:

{
    "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
}

Why its not saving the push in the board object?

1
  • why all comments deleted? Commented Sep 18, 2020 at 11:56

1 Answer 1

2

Mongoose is weird. You need to mark the field as modified, otherwise the changes won't be saved. Try this :

board.markModified("boardLists");
await board.save();
Sign up to request clarification or add additional context in comments.

Comments

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.