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

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

问题描述

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

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.

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

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