【问题标题】:Removing many to many reference in Mongoose删除 Mongoose 中的多对多引用
【发布时间】:2013-11-29 07:42:10
【问题描述】:

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

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

【问题讨论】:

    标签: node.js mongodb mongoose many-to-many nosql


    【解决方案1】:

    您在使用'remove' 中间件的正确轨道上。在中间件函数中,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 上建立索引以获得良好的性能。

    【讨论】:

    • 如果groups 没有被索引,你将强制对用户进行全表扫描和数组扫描。
    • @WiredPrairie 如果双重链接的参考可靠,则有一种解决方法。我将其添加为更好的选择。
    • 看起来很真实,但是 this.model('user') 怎么能工作,因为 this 指的是组模式,this.model 不是函数
    • @SuhaybKharabsheh this 指的是组模型实例(被删除的文档),它确实有一个model method。
    【解决方案2】:

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

    布鲁诺·格罗西

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2016-10-28
      • 2020-09-22
      • 1970-01-01
      相关资源
      最近更新 更多