gpt4 book ai didi

node.js - Mongoose 级联中间件,多层次

转载 作者:可可西里 更新时间:2023-11-01 10:21:05 25 4
gpt4 key购买 nike

我正在尝试让级联“删除”中间件在 mongoose 上运行。

我有一个数据库:

'modules' -> 'modulesInst' -> 'assignments' -> 'studentAssignments'

所以当模块删除时,它会级联'modulesInst',当modulesInst删除时,它会删除'assignments'相关的,然后与'student assignments'相同。

问题是我只能让它在一个级别上工作。

顶级架构和“删除”中间件(模块)

var modulesSchema = new Schema (
{
_id: Number,
moduleName: String,
moduleLeader: String
}
);

modulesSchema.pre('remove', function(next){
modulesInst.remove({modID: this._id}).exec();
next();
});

二级架构和“删除”中间件 (moduleInst) [中间件停止级联的地方]

var modulesInstSchema = new Schema (
{
year: Number,
semester: String,
modID: [{ type: Schema.Types.Number, ref: 'Module' }],
}
);

modulesInstSchema.pre('remove', function (next) {
assignment.remove({modInsID: this._id}).exec();
next();
});

第三级架构和“删除”中间件(赋值)[中间件也不会触发]

var assignmentSchema = new Schema (
{
code: String,
assignName: String,
modInsID: [{ type: Schema.Types.Number, ref: 'ModuleInst' }],
}
);

assignmentSchema.pre('remove', function (next) {
studentAssign.remove({assID: this._id}).exec();
next();
});

我是否缺少保持级联的简单技巧?由于文档不明确,找不到示例。

最佳答案

Model.remove() 方法不会触发中间件。来自docs :

Note: There is no query hook for remove(), only for documents. If you set a 'remove' hook, it will be fired when you call myDoc.remove(), not when you call MyModel.remove().

也就是说,您必须在文档级别执行此操作,例如(使用 bluebird 的 promise ):

modulesInt
.find({ modID: this._id })
.then((modules) => Promise.each(modules, (module) => module.remove()))
.then(next)
.catch(next)

关于node.js - Mongoose 级联中间件,多层次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39409183/

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