Jason McFarlane
Jason McFarlane

Reputation: 2175

Remove entire objects by array of ids

I have an array of objects that contains metadata and looks similar to this.

Data:

metadata:[ 
  { matchid: '1', region: 'europe' }, 
  { matchid: '2', region: 'africa' },
  { matchid: '3', region: 'asia' },
]

I have an endpoint setup to receive an array of IDS ['1', '2'] which would the remove all the objects containing these IDS.

This is my current query:

Query to remove objects

xx.findByIdAndUpdate(
    id,
    $pullAll: {
        "metadata.matchid": {
           $in: req.body.matches
        }
    }
)

I am expecting both objects with the ids of 1 and 2 to be removed

Expected Results:

metadata:[ 
  { matchid: '3', region: 'asia' },
]

I am recieving an error I have never seen before it is an object that says codeName: "BadValue"

Upvotes: 0

Views: 31

Answers (1)

J.F.
J.F.

Reputation: 15187

As documentation says:

The $pullAll operator removes all instances of the specified values from an existing array. Unlike the $pull operator that removes elements by specifying a query.

$pullAll requires and exact match and $pull is like to use a filter. So you can use $pull in this way.

yourModel.findByIdAndUpdate(
    id,
    $pull: {
        metadata:{
           matchid: { $in: req.body.matches}
        }
    }
)

Example here

Upvotes: 1

Related Questions