Thursday, 16 March 2017

Mongoose: Remove ($pull) from nested array

i had a look at several threads, but i cannot manage to get this to work:

My model looks like this:

let UserSchema = new Schema({
    [...]
    feed: [
    {
        seen: Boolean,
        isOwnEntity: Boolean,
        activity: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Activity'
    }
    }, {_id: false}],
    [...]
});

I now want to remove entries in this feed with an update, but the update does not work:

User.update({'feed': {'$elemMatch': {'activity': this._id}}}, {'$pull': {'feed': {'activity': this._id}}});

I tried with and without $elementMatch, according to: https://docs.mongodb.com/manual/reference/operator/update/pull/#up._S_pull

A find() works, though:

    User.find({'feed': {'$elemMatch': {'activity': this._id}}}).exec().then((users) => {
       users.forEach((user) => {
           user.feed = user.feed.filter((entry) => {
               return !entry.activity.equals(this._id);
           });
       user.save();
   });
});



via Tobias Stangl

No comments:

Post a Comment