Node.js/猫鼬-撤消对错误的数据库修改 [英] Node.js / Mongoose - Undo Database Modifications on Error

查看:135
本文介绍了Node.js/猫鼬-撤消对错误的数据库修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的node.js服务器中有一条非常复杂的express路由,该路由通过mongoose对数据库进行了许多修改.

I have quite a complex express route in my node.js server, that makes many modifications to the database via mongoose.

我的目标是实现一种机制,该机制会在发生任何错误时还原所有更改.我的想法是实现撤消catch块的功能.

My goal is to implement a mechanism, that reverts all changes when any error occurs. My idea was implementing functions for undoing into the catch block.

但这很丑陋,因为我必须知道以前的值是什么,如果catch块中发生错误怎么办?当Promise.all(array.map( /* ... */ ))

But this is quite ugly, as I have to know what the previous values were and what if an error occurs in the catch block? It's especially difficult to revert those changes, when an error occurred during a Promise.all(array.map( /* ... */ ))

我的路线与此类似:

module.exports = (req, res) => {

    var arr1, var2, var3

    try {

        const body = req.body

        arr1 = await fetchVar1(body)
        const _data = await Promise.all([
            Promise.all(
                arr1.map(async x => {
                    const y = await fetchSometing(x)
                    return doSometing(y)
                })
            ),
            doSomething3(arr1),
        ])
        var2 = _data[1]
        var3 = _data[2]

        return res.json({ arr1, var2, var3 })

    } catch (err) {

        /**
         * If an error occurs I have to undo
         * everything that has been done
         * in the try block
         */

    }
}

最好,我希望实现一些可以批处理"所有更改并在未发生错误的情况下提交"更改的东西.

推荐答案

您正在寻找的是交易: https://mongoosejs.com/docs/transactions.html

What you are looking for is transactions: https://mongoosejs.com/docs/transactions.html

在完成操作后手动撤消操作并不能保护您免受所有问题的困扰,因此您不应依赖它.例如,正如您所写的:如果在部分写入(某些数据已写入,有些是注释)之后发生崩溃,然后在您的回滚"代码期间又发生了崩溃而又没有清除所有内容,那么会发生什么情况呢?如果您的代码依赖于绝对干净的数据,那么您就有问题了.您的代码应该能够正确处理部分数据,或者您必须有某种方法来确保您的数据在任何时候都完美无缺.

Manually undoing stuff after doing them won't protect you from every issue, so you should not rely on that. For example, exactly as you wrote: what happens if there is a crash after a partial write (some data is written, some is note), then another crash during your "rollback" code, which does not cleanup everything? If your code depends on your data being absolutely clean, then you have a problem. Your code should either be able to handle partial data correctly, or you must have some way to guarantee that your data is perfectly good at all times.

事务是要走的路,因为它只有在一切正常的情况下才一次提交所有内容.

Transactions is the way to go, because it only commits everything at once if everything works.

这篇关于Node.js/猫鼬-撤消对错误的数据库修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆