mongo-tx
A flexible & extensible mongodb transaction library.
Install
npm i --save mongo-tx
or
yarn add mongo-tx
How to
Intro
When you create a transaction and run it, You need to use model wrappers to modify data during transactions, each model wrapper would create lock and snapshot before find/findOne/create/modifie/remove documents, after all operations of these documents in this transaction have succeeded, transaction manager will remove all snapshots and release all locks (committing). If error happened in this transaction, all changed documents will be replaced by snapshots and locks will also be released (rollingback).
Lock
Built-in lock is implemented by mongo's unique key, and using jdarling/MongoMQ to create a waiting lock. You can create your own lock by redis, ssdb or other library.
NOTICE:
- This kind of lock won't work like any relational database, you need to manually acquire a lock to make sure it's a synchronized operation. If you need to make sure "the locked document" in transaction is also locked in any other place, you'd better create a transaction for it, or acquire a document lock:
- Waiting lock is not safe as you expected, it would fail in many cases, like too much transactions using same lock to cause time out, loop locks cause dead lock and time out (tx1 need lock acc1 & acc2, it has locked acc1; tx2 need lock acc2 & acc1, and it has locked acc2, then they would both fail with time out error), e.g. Just make sure you know waiting lock would fail.
const lock = runTxawait lock// do somethingawait lock
Fix process crash
If your whole process is crashed during the transaction, call runTx.fixCrash()
after your process restarted (and make sure mongodb is connected), this function would try to rollback running/rollingback
transactions, and commit committing
onces.
WriteConcern
All collections in this library is using { w: 1, j: 1 }
to make sure writing to journal, and you can change it if needed.
Usage
const runTx = /** * @param * @param * @param * @type {[type]} */await // other code
TxModel
/** * insert document * @param * @return */ { // ... } /** * find documents * @param * @return */ { // ... } /** * find one document * @param * @return */ { // ... } /** * findOneAndUpdate * @param * @param * @param * @return */ { // ... } /** * findOneAndRemove * @param * @param * @return */ { // ... }
Tips
For more use case please see test folder.
For more options please see each implements.