Home > Net >  How to remove object from array in Mongoose using updateMany?
How to remove object from array in Mongoose using updateMany?

Time:10-14

I am trying to get an object removed from an array in MongoDB using Mongoose/Node and so far I have been unable to get it removed. I have read docs and SO posts to no luck. I'm hoping someone could give me specific advice on a solution not just a link to another post which is vaguely related

Mongo document example

{
  managers: [{
      userID: value,
      // other fields and values
    },
  // Another object for another manager
  ]
}

Code I am trying to use

await Model.updateMany(
  {'managers.userID': userID}, // This should be the query part
  {$pullAll: {'managers': {'userID': userID}}} // This should be the update part
)

CodePudding user response:

Using $pullAll you have to match the whole object.

Apart from the syntax is not correct in your query, check how in this example the id 1 is not removed but it is the id 2. That's because $pullAll expects to match the whole object. And this other example works removing both ids.

Then, to do your query you can use $pull and $in like this:

await Model.updateMany({
  "managers.userID": userID
},
{
  "$pull": {
    "managers": {
      "userID": {
        "$in": userIDs
      }
    }
  }
})

Example here

Note how $in expects an array. If you only want to remove based on one value you can avoid $in:

await Model.updateMany({
  "managers.userID": userID
},
{
  "$pull": {
    "managers": {
      "userID": userID
    }
  }
})

Example here

  • Related