One of my mongoose schemas is a many to many relationship:
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 remove a group, is there anyway to remove that group objectId from all the user's 'groups' array?
GroupSchema.pre('remove', function(next){
//Remove group._id from all the users
})
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 itsmodel
method. So you can do something like:Or if you want to support cases where the
users
field in your group instance may not be complete you could do:But as WiredPrairie notes, for this option you'd want an index on
groups
for good performance.I use my patched version of mongoose-relationship "plugin" to solve this: take a look on https://github.com/begrossi/mongoose-relationship/tree/remove-from-parent-if-removed-from-child-set.
Bruno Grossi