在猫鼬中删除多对多参考 [英] Removing many to many reference in Mongoose

查看:73
本文介绍了在猫鼬中删除多对多参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的猫鼬模式之一是多对多关系:

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

如果我删除了一个组,是否仍然可以从所有用户的组"数组中删除该组objectId?

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
})

推荐答案

为此,您可以使用'remove'中间件了.在中间件功能中,this是要删除的组实例,您可以通过其model方法访问其他模型.因此,您可以执行以下操作:

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 its 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
    );
});

或者如果您想支持某些情况,例如您的组实例中的users字段可能不完整,则可以这样做:

Or if you want to support cases where the users field in your group instance may not be complete you could do:

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

但是正如WiredPrairie指出的那样,对于此选项,您希望在groups上建立索引以取得良好的性能.

But as WiredPrairie notes, for this option you'd want an index on groups for good performance.

这篇关于在猫鼬中删除多对多参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆