Mongoose.js transactions

前端 未结 6 1009
栀梦
栀梦 2021-01-30 18:14

I know MongoDB doesn\'t support transactions as relational databases do, but I still wonder how to achieve atomicity for several operations. Hunting around the web, I see people

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 18:38

    There have been a few attempts to implement solutions. None of them are particularly active at the time of writing. But maybe they work just fine!

    • https://github.com/anand-io/mongoose-transaction Lacks documentation, 1 year idle.

    • https://github.com/niahmiah/mongoose-transact Documented, 2 years idle.

    • https://github.com/rain1017/memdb Offers transaction support but actually does a lot more than just that, 6 months idle.

    niahmiah's README is worth looking at. It notes some disadvantages of using transactions, namely:

    • All updates and removals for the relevant collections should go through the transaction processor, even when you weren't intentionally doing a transaction. If you don't do this, then transactions may not do what they are supposed to do.
    • Those updates, as well as the transactions you initially wanted, will be significantly slower than normal writes.

    niahmiah also suggests that there may be alternatives to using transactions.


    Just a tip: If you don't like the idea of locking up your frequently used collections, you could consider separating the sensitive (transactional) data from the less sensitive data.

    For example, if you are currently holding credits in the User collection, then you would be better off separating it into two collections: User and UserWallet, and moving the credits field into the wallets. Then you can freely update User documents without fear of interfering with transactions on the UserWallet collections.

提交回复
热议问题