猫鼬 |中间件 |抛出错误时由 pre/post 钩子执行的回滚操作

问题描述

考虑下面的代码,当在任何钩子中抛出错误时,如何实现事务以确保 someParentDocument 不会被删除并且钩子内执行的任何操作都将回滚?


const parentSchema = new mongoose.Schema({
    name: String,children: [{ type: mongoose.Schema.Types.ObjectId,ref: "Child" }],});

const childSchema = new mongoose.Schema({
    name: String,parent: { type: mongoose.Schema.Types.ObjectId,ref: "Parent" },});

parentSchema.pre("remove",async function(next){
    // Add and remove documents to Parent and Child...
    //...
    next();
});

parentSchema.post("remove",async function(parent){
    throw new Error("Exception!");
});


// (...)
try {
    await someParentDocument.delete();  // <-- will trigger the hooks above
} catch {}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)