Finding nested object and updating it

hi all,
i have my document as follows.

[
        {
            "_id": "642fe50af4723c9936dbb366",
            "name": "test two",
            "priority": 0,
            "users": [
                {
                    "admin": false,
                    "role": 3,
                    "_id": "642fe553a1b8adf605c53167"
                },
                {
                    "admin": false,
                    "role": 1,
                    "_id": "642bf3865808d8888a1995b4"
                }
            ],
            "createdAt": "2023-04-07T09:40:26.550Z",
            "updatedAt": "2023-04-07T09:50:13.354Z",
            "__v": 0
        }
    ]

i would like to search this collection by ID,
then search users by ID ,
and update the user by specific fields that come from req.body

so fr i have tried a few methods:

  const projects = await Project.findOneAndUpdate(
      {
        _id: projectId,
        "users._id": user._id,
      },
      {
        $set: {
          users: update,
        },
      }
    );

The problem with this is that it changes the whole users array not the specific user.
anyone so kind to help me out would be hugely appreciated

and also

 const projects = await Project.findOneAndUpdate(
      { projectId },
      { $set: { users: update } },
      { arrayFilters: [{ "users._id": user._id }] }
    );

which seems the right way however i get

MongoServerError: The array filter for identifier 'users' was not used in the update { $setOnInsert: { createdAt: new Date(1680862292699) }, $set: { users: [ { admin: false, role: 3, _id: ObjectId('642fec54b0a5eea143444e16') } ], updatedAt: new Date(1680862292699) } }

this worked for me :slight_smile:

const projects = await Project.findOneAndUpdate(
      {
        _id: projectId,
        "users._id": user._id,
      },

      {
        $set: { "users.$": { ...update, _id: user._id } },
      },
      {
        new: true,
      }
    );

for any beginners like myself who struggle a little bit, please note “users.$” where $ tells to only update that specific user

1 Like