Delay when updating document (MongoDB/Mongoose)

Issue

In my application, I am attempting to update a object nested in an array as a below. When testing in postman, there is a delay causing me to have to make two requests in order to see the updated value.

if (taskStatus) {
    const taskStatusNew = await Board.findOneAndUpdate(
      {
        "columns.tasks._id": req.params.id,
      },
      {
        $set: {
          "columns.$[].tasks.$[t]": req.body,
        },
      },
      {
        arrayFilters: [
          {
            "t._id": req.params.id,
          },
        ],
      }
    );
    res.status(200).json(taskStatusNew);
  }

Solution

By default, findOneAndUpdate() returns the document as it was before the update was applied. So you have to set the new option to true if you are using mongoose.

const taskStatusNew = await Board.findOneAndUpdate(
      {
        "columns.tasks._id": req.params.id,
      },
      {
        $set: {
          "columns.$[].tasks.$[t]": req.body,
        },
      },
      {
        arrayFilters: [
          {
            "t._id": req.params.id,
          },
        ],
        new: true
      }
    );

Documentation article for reference: https://mongoosejs.com/docs/tutorials/findoneandupdate.html

Answered By – Dezzley

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published