Node.js / Mongoose - Undo Database Modifications on Error

百般思念 提交于 2019-12-06 08:26:37

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.

What you’re looking for is called Transactions.

Transactions are new in MongoDB 4.0 and Mongoose 5.2.0. Transactions let you execute multiple operations in isolation and potentially undo all the operations if one of them fails. This guide will get you started using transactions with Mongoose.

For more information check the link below: https://mongoosejs.com/docs/transactions.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!