Jason McFarlane
Jason McFarlane

Reputation: 2175

Mongoose add/remove items from nested array

I have a document that has a nested array that I need to add/remove items from. Normally you query a nested object by id but in this case a dynamic object _id wont work and I need to update by the nested profile id.

Document

{
    title: 'Title',
    members: [
      { 
          profile: { id: '123', name: 'Foo' },
          items: ['id1', 'id2', 'id3']
      }
    ]
}

Query

My thinking is I need some sort of $elemMatch & $pushAll combo but cant seem to get it working. For removing items from the array I would swap push for pull

await this.repo.findByIdAndUpdate(id, {
    members: {
        $elemMatch: { 'profile.id': '123' },
        $pushAll: {
            items: ['xxx', 'yyy'],
        },
    },
})

Upvotes: 0

Views: 384

Answers (1)

R2D2
R2D2

Reputation: 10737

You need to use arrayFilters & $push with $each since $pushAll has been deprecated

db.collection.update({},
{
 $push: {
   "members.$[x].items": {
     $each: [
       "xxx",
       "yyy"
     ]
   }
 }
},
 {
  arrayFilters: [
    {
     "x.profile.id": "123"
    }
  ]
})

playground

Upvotes: 0

Related Questions