gpt4 book ai didi

node.js - 删除 Mongoose 中的多对多引用

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:25 26 4
gpt4 key购买 nike

我的 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'中间件来实现此目的是正确的。在中间件函数中,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 所指出的,对于此选项,您需要在上建立索引以获得良好的性能。

关于node.js - 删除 Mongoose 中的多对多引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com