Reputation: 13164
In Mongoose model User given document look like this:
> db.users.find().pretty()
{
/* ... */
"events" : [
{
"_id" : ObjectId("537bb2faf87f9a552c3219ea"),
"message" : "Foo"
},
{
"_id" : ObjectId("537bb436c3b9a1aa2db71b7c"),
"message" : "Bar"
},
{
"_id" : ObjectId("537bb4ab2cc503e52e24d145"),
"message" : "Biz"
},
{
"_id" : ObjectId("537bb4d02cc503e52e24d146"),
"message" : "Pop"
}
]
}
Some function takes event _id as parameter and must delete object responding to this _id from MongoDB. I tried:
User
.findByIdAndUpdate(req.user._id, {
$pull: {events: {
$elemMatch: {_id: _eventId} //_eventId is string representation of event ID
}}
}, function(err) {
// ...
});
It is not working. What am I doing wrong?
Upvotes: 4
Views: 1843
Reputation: 42048
Quote from SERVER-2016:
The argument to $pull is already applied to each element of the target array, so using $elemMatch is redundant in the update context.
So just execute your query without $elemMatch
:
User
.findByIdAndUpdate(req.user._id, {
$pull: {events: {
_id: _eventId //_eventId is string representation of event ID
}}
}, function(err) {
// ...
});
Upvotes: 4