skip to Main Content

My data structure looks as follows

[
        {
            "_id": "642e9f78abebcdd68147d6aa",
            "name": "test two",
            "priority": 0,
            "users": [
                {
                    "admin": true,
                    "role": 3,
                    "_id": "642aa3df4add92f56fe8caab"
                },
                {
                    "admin": false,
                    "role": 1,
                    "_id": "642bf3865808d8888a1995b4"
                }
            ],
            "createdAt": "2023-04-06T10:31:20.033Z",
            "updatedAt": "2023-04-06T10:31:27.863Z",
            "__v": 0
        }
    ]

I would like to find the project by id ( "_id": "642e9f78abebcdd68147d6aa")

then find the user by id ("_id": "642aa3df4add92f56fe8caab")

and update the user.

I tried to findOne and update

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

however, this approach updates the whole "users" array instead of just one specific one that matches the search.

my next attempt was:

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

however, this gives me the following error

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) } }

2

Answers


  1. Chosen as BEST ANSWER

    I have found the answer, to update such nested files you can use the following:

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

  2. You can use $elemMatch like below and use this object in to mongoose query. I think it will help you.

    {
    _id:"642e9f78abebcdd68147d6aa",
    users: { $elemMatch: { _id:"642aa3df4add92f56fe8caab"}
    }
    

    More clarification about $elemMatch visit this link https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search