Removing many, many links in Mongoose

One of my mongoose patterns is many, many relationships:

var UserSchema = new Schema({ name : String, groups : [ {type : mongoose.Schema.ObjectId, ref : 'Group'} ] }); var GroupSchema = new Schema({ name : String, users : [ {type : mongoose.Schema.ObjectId, ref : 'User'} ] }); 

If I delete a group, is this groupId object deleted from all arrays of user groups anyway?

 GroupSchema.pre('remove', function(next){ //Remove group._id from all the users }) 
+8
mongodb mongoose nosql many-to-many
source share
2 answers

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.

+15
source share

I am using my patched version of mongoose-relationship "plugin" to solve this problem: take a look at https://github.com/begrossi/mongoose-relationship/tree/remove-from-parent-if-removed-from-child-set .

Bruno Grossi

0
source share

All Articles