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.
- Create variables used in the transaction.
- Start a new session.
- Begin a transaction with the
WithTransaction()method on the session. - Update the
balancefield of the sender’s account by decrementing thetransaction_amountfrom thebalancefield. - Update the
balancefield of the receiver’s account by incrementing thetransaction_amountto thebalancefield. - Create a transfer document and insert it into the
transferscollection. - Update the
transfers_completearray of the sender’s account by adding thetransfer_idto the array. - Update the
transfers_completearray of the receiver’s account by adding thetransfer_idto the array. - Log a message regarding the success or failure of the transaction.
- Catch any errors and close the session.
// 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 = 100const session = client.startSession()const transactionResults = await session.withTransaction(async () => {
// Operations will go here
})const senderUpdate = await accounts.updateOne(
{ account_id: account_id_sender },
{ $inc: { balance: -transaction_amount } },
{ session }
)const receiverUpdate = await accounts.updateOne(
{ account_id: account_id_receiver },
{ $inc: { balance: transaction_amount } },
{ session }
)const transfer = {
transfer_id: "TR21872187",
amount: 100,
from_account: account_id_sender,
to_account: account_id_receiver,
}
const insertTransferResults = await transfers.insertOne(transfer, { session })
const updateSenderTransferResults = await accounts.updateOne(
{ account_id: account_id_sender },
{ $push: { transfers_complete: transfer.transfer_id } },
{ session }
)const updateReceiverTransferResults = await accounts.updateOne(
{ account_id: account_id_receiver },
{ $push: { transfers_complete: transfer.transfer_id } },
{ session }
)if (transactionResults) {
console.log("Transaction completed successfully.")
} else {
console.log("Transaction failed.")
}} catch (err) {
console.error(`Transaction aborted: ${err}`)
process.exit(1)
} finally {
await session.endSession()
await client.close()
}