Lesson 6: Creating MongoDB Transactions in Node.js Applications / Learn

Creating MongoDB Transactions in Node.js Applications

Review the following code, which demonstrates how to create multi-document transactions in MongoDB with Node.js.


Creating a Transaction

In this section, we'll go through the code to create a transaction step by step. We start the transaction by using the session’s withTransaction() method. We then define the sequence of operations to perform inside the transactions, passing the session object to each operation in the transactions.



  1. Create variables used in the transaction.
  2. // Collections
    const accounts = client.db("bank").collection("accounts")
    const transfers = client.db("bank").collection("transfers")
    
    // Account information
    let account_id_sender = "MDB574189300"
    let account_id_receiver = "MDB343652528"
    let transaction_amount = 100

  3. Start a new session.
  4. const session = client.startSession()

  5. Begin a transaction with the WithTransaction() method on the session.
  6. const transactionResults = await session.withTransaction(async () => {
      // Operations will go here
    })

  7. Update the balance field of the sender’s account by decrementing the transaction_amount from the balance field.
  8. const senderUpdate = await accounts.updateOne(
      { account_id: account_id_sender },
      { $inc: { balance: -transaction_amount } },
      { session }
    )

  9. Update the balance field of the receiver’s account by incrementing the transaction_amount to the balance field.
  10. const receiverUpdate = await accounts.updateOne(
      { account_id: account_id_receiver },
      { $inc: { balance: transaction_amount } },
      { session }
    )

  11. Create a transfer document and insert it into the transfers collection.
  12. const transfer = {
      transfer_id: "TR21872187",
      amount: 100,
      from_account: account_id_sender,
      to_account: account_id_receiver,
    }
    
    const insertTransferResults = await transfers.insertOne(transfer, { session })

  13. Update the transfers_complete array of the sender’s account by adding the transfer_id to the array.
  14. const updateSenderTransferResults = await accounts.updateOne(
      { account_id: account_id_sender },
      { $push: { transfers_complete: transfer.transfer_id } },
      { session }
    )

  15. Update the transfers_complete array of the receiver’s account by adding the transfer_id to the array.
  16. const updateReceiverTransferResults = await accounts.updateOne(
      { account_id: account_id_receiver },
      { $push: { transfers_complete: transfer.transfer_id } },
      { session }
    )

  17. Log a message regarding the success or failure of the transaction.
  18. if (transactionResults) {
      console.log("Transaction completed successfully.")
    } else {
      console.log("Transaction failed.")
    }

  19. Catch any errors and close the session.
  20. } catch (err) {
      console.error(`Transaction aborted: ${err}`)
      process.exit(1)
    } finally {
      await session.endSession()
      await client.close()
    }