Reputation: 9549
OBJECTIVE: I am creating a simulated transaction, involving exchange of a certain sum between two accounts. (using NodeJS server and Mongoose)
| ACCOUNT1 | ACCOUNT2 | (Account Balance)
--------------------------------
T1.| 5000 | 2000 | (initial values)
--------------------------------
T2.| 3000 | 4000 | (ACCOUNT1 transfers 2000 to ACCOUNT2)
--------------------------------
PROBLEM: The problem lies in the fact that each transaction T1, T2 requires of two actions:
Failure of any of these two should cause a rollback in the other
CURRENT APPROACH:
// save transaction log.then(function(data){
AccountHelper.updateAccount(accountOwner, fromAccount, amount)
.then(function(data){
AccountHelper.updateAccount(accountOwner, fromAccount, amount)
.then(function(data){
//some success response
}).catch(function(err){
// rollback the previous update
// respond with the err
});
})
.catch(function(err){
// respond with the err
});
//}).catch(function(err){ respond with the err});
Is there a better way to do this? Another way I can think of doing this is:
Event emitter way:
Also note, any transaction can be deleted at any time in future which must reflect in the current balance (the sum involved in the transaction must get restored to the original account).
Upvotes: 0
Views: 249
Reputation: 36319
Generally, don't. As the author of the mongoose-transact module eloquently says, transactions were excluded from Mongodb for a reason.
https://www.npmjs.com/package/mongoose-transact
Upvotes: 1