Amresh Venugopal
Amresh Venugopal

Reputation: 9549

Updating dependent fields with mongoose

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:

  1. Update account 1
  2. Update account 2

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:

  1. Save transaction log.
  2. Emit an event.
  3. Event handler takes snapshot of the collections mentioned in the transaction log.
  4. Update the collections
  5. If any updation fails, rollback by snapshot.

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

Answers (1)

Paul
Paul

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

Related Questions