在Mongoose中删除多个参考

我的一个mongoose模式是一个多对多的关系:

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'} ] }); 

如果我删除一个组,是否有从所有用户的“组”数组中删除该组objectId?

 GroupSchema.pre('remove', function(next){ //Remove group._id from all the users }) 

您正在为此使用'remove'中间件。 在中间件function中, this是组实例被删除,您可以通过其model方法访问其他模型。 所以你可以做这样的事情:

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

或者,如果您要支持群组实例中的users字段可能不完整的情况,您可以执行以下操作:

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

但是WiredPrairie指出,对于这个选项,你需要一个关于groups的索引来获得良好的性能。

我使用我的补丁版本的mongoose关系“插件”来解决这个问题:看看https://github.com/begrossi/mongoose-relationship/tree/remove-from-parent-if-removed-from-child-设置 。

布鲁诺·格罗西