在没有副本集或尽可能少的配置的情况下启用 MongoDB 个事务

Enabling MongoDB transactions without replica sets or with least possible configuration

[一些背景信息 - 可能会跳过]

To begin with, I have barely any understanding of database management and just shallow experience with mongoose and node in the backend realm(a couple of udemy courses). Udemy courses made me believe that mongodb was still a viable choice for a database with relational properties and off I went working on a backend for a forum-like website. After learning about transactions, I attempted to implement them in my backend, since it seemed perfectly necessary to implement a rollback feature when executing an array of queries. However it turns out that transactions are only possible on replica sets - which also appeared to require a minimum of 2. 3 databases for a startup MVP was obviously considered an overkill.

[问题]

  1. 是否可以只用1个数据库实现事务?如果有怎么办?

  2. 如果以上不可能,那么在实施事务时如何以最低配置启动 mongodb 数据库,考虑到该数据库是用于启动 MVP 的。

  3. (对于任何有在类似场景中实现生产级 mongo 数据库经验的人)如果不考虑使用事务,如何发送查询 editing/creating 多个无需事务即可安全地将文档记录到 mongoDB 数据库,同时不会使用由查询组成的 try-catch 喷洒每一位代码以回滚每个故障点(我认为这是太多的开销)

我的截止日期很紧,并且已经使用 mongoose 完成了大量的基础工作和一些路线,这意味着为关系数据库放弃 mongodb 将是一个困难目前的选项。

我想我已经 google 搜索了与该主题相关的所有内容,甚至在 google 搜索的第二页尝试了博客/文章(包括我自己在内的许多人认为这是黑暗的网页/s)。 但我确实认为我可能错过了我要找的东西,也欢迎仅包含链接的答案。

感谢阅读!

您需要一个副本集[*]才能使用事务,但您可以创建一个单节点副本集以进行测试。

描述了完整的过程 in documentation,对于单节点 RS,您可以按照所写的那样进行操作,但只配置一个成员。

简而言之,您需要将 --replSet 参数传递给 mongod,然后通过 mongo shell 和 运行 rs.initiate() 连接到它.

请注意,交易并不是解决所有问题的灵丹妙药。在某些情况下它们是合适的,在某些情况下 MongoDB 提供更适合的其他功能。

[*] 或 MongoDB 4.2+ 的分片集群,但这涉及更多的设置工作。