Steps for the Transaction
<aside> ⚠️ Multi-document transactions have a 60-second time limit
</aside>
// 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
const session = client.startSession()
WithTransaction() method on the session.const transactionResults = await session.withTransaction(async () => {
// Operations will go here
})
balance field of the sender’s account by decrementing the transaction_amount from the balance field.const senderUpdate = await accounts.updateOne(
{ account_id: account_id_sender },
{ $inc: { balance: -transaction_amount } },
{ session }
)
balance field of the receiver’s account by incrementing the transaction_amount to the balance field.const receiverUpdate = await accounts.updateOne(
{ account_id: account_id_receiver },
{ $inc: { balance: transaction_amount } },
{ session }
)
transfers collection.const transfer = {
transfer_id: "TR21872187",
amount: 100,
from_account: account_id_sender,
to_account: account_id_receiver,
}
const insertTransferResults = await transfers.insertOne(transfer, { session })
transfers_complete array of the sender’s account by adding the transfer_id to the array.const updateSenderTransferResults = await accounts.updateOne(
{ account_id: account_id_sender },
{ $push: { transfers_complete: transfer.transfer_id } },
{ session }
)