删除猫鼬中的多对多引用 [英] Removing many to many reference in Mongoose

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

问题描述

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

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天全站免登陆