Search code examples
databasemongodbmongoose-schema

How to replace array element inside array of object


I have the following schema in mongodb

  teamMembers: [
    {
      employeeId: {
        type: Array,
        required: true,
      },
      role_id: {
        type: String,
        required: true,
      },
    },
  ],

i want to replace employeeId wtih another existing id. To do so i tried following

let event = await eventsModel.updateOne(
 {
    _id: info.eventId,
    "teamMembers.employeeId": req.body.leaveSeekerId,
    },
    {
      set: { "teamMembers.$[elem].employeeId.$[]": info.replacement },
     },
     {
       arrayFilters: [{ "elem.employeeId": req.body.leaveSeekerId }],
     }
  } 
 );

but by doing this all ids exist in employeeId array are replaced by new id


Solution

  • You're using Mongo's array positional all identifier $[] , from the docs:

    The all positional operator $[] indicates that the update operator should modify all elements in the specified array field.

    So you are telling him to modify all elements in the nested array, this can easily be solved if you just add an identifier similar to how you added it to the parent element, like so:

    db.collection.updateOne({
      "teamMembers.employeeId": req.body.leaveSeekerId,
    },
    {
      $set: {
        "teamMembers.$[elem].employeeId.$[elem2]": info.replacement
      },
      
    },
    {
      arrayFilters: [
        {
          "elem.employeeId": req.body.leaveSeekerId,
        },
        {
          "elem2": req.body.leaveSeekerId,
        }
      ],
    })
    

    Mongo Playground