MongoDB
 SQL >> Base de Dados >  >> NoSQL >> MongoDB

Limpando referências many-to-many ao excluir com middleware Mongoose

Use middleware 'remove':

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

Se this.users puder estar incompleto, case pelo outro lado:

this.model('User').update({ groups: this._id }, { $pull: { groups: this._id } }, { multi: true }, next)

Coloque índice em groups.