You are on the right track to use the 'remove' middleware for this. In the middleware function this group instance is deleted and you can access other models using the 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 an instance of your group may be incomplete, you can 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 need an index on groups for good performance.
Johnnyhk
source share