Best practices when updating deeply nested objcects?

I have a document like this

    {
      _id: 613c0f13f94240e957e272b9,
      name: "starter Weekly diary",
      nutritionstats: {...},
      currentDay: 1,
      days: [
    {name: "day 1", uid: 108, foods: [...]},
    {name: "day 2", uid: 107, foods: [...]},
    {name: "day 3", uid: 109 foods: [...]},
      ]
    }

Let’s say that I want to update the second elements name property in the days array. Do I simply pass entire new object with updated info, or do I query the database like this and only update that property?

app.patch("/currentmealplan/testarrayfilter/:userid", async (req, res) => {
  try {
    const newName = req.body.name;
    const currentdiary = await Diary.findByIdAndUpdate(
      req.params.userid,
      {
        $set: {
          "days.$[elemX].name": newName,
        },
      },
      {
        arrayFilters: [
          {
            "elemX.uniqueId": "107",
          },
        ],
      }
    );
    res.sendStatus(200);
  } catch (error) {
    res.send(error);
  }
});

So basically are there benefits in making fractional updates and making many api calls like this:

app.patch("/diary/changesingledayname/:userid", async (req, res) =>...

app.patch("/diary/addexercise/:userid", async (req, res) =>...

app.patch("/diary/removeexercise/:userid", async (req, res) =>...

app.patch("/diary/addday/:userid", async (req, res) =>...

app.patch("/diary/removeday/:userid", async (req, res) =>...

Hi @Lukas_Visinskis,

I would vote for the fractional updates because if you send the entire new object, there is a chance that you are overwriting a concurrent write operation that is happening in parallel. With the fractional update, your operation is completely atomic.

Cheers,
Maxime.

1 Like