我正在尝试让级联“删除”中间件在 Mongoose 上工作。
我有一个数据库:
'modules' -> 'modulesInst' -> 'assignments' -> 'studentAssignments'
因此,当模块删除时,它会级联'modulesInst',当modulesInst删除时,它会删除相关的'作业',然后与'学生作业'相同。
问题是我只能让它在一个级别上工作。
顶级架构和“删除”中间件(模块)
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/