Removing many to many reference in Mongoose Removing many to many reference in Mongoose mongoose mongoose

Removing many to many reference in Mongoose


You're on the right track to use 'remove' middleware for this. In the middleware function, this is the group instance being removed and you can access the other models via its model method. So you can do something like:

GroupSchema.pre('remove', function(next){    this.model('User').update(        {_id: {$in: this.users}},         {$pull: {groups: this._id}},         {multi: true},        next    );});

Or if you want to support cases where the users field in your group instance may not be complete you could do:

GroupSchema.pre('remove', function(next){    this.model('User').update(        {groups: this._id},         {$pull: {groups: this._id}},         {multi: true},        next    );});

But as WiredPrairie notes, for this option you'd want an index on groups for good performance.