I am using MongoDB transactions as the following example shows and I am wondering if there is a way to cancel the updating transaction programmatically in case the following step fails.
const session = client.startSession();
try {
await session.withTransaction(async () => {
await coll1.insertOne({ abc: 1 }, { session });
await coll2.insertOne({ xyz: 999 }, { session });
}, transactionOptions);
// Now that the DB is updated, I'll try to use a service
const result = paymentProcessor.chargeCard(billingDetails, 200);
if(result.error) **cancelTransactionAndRestoreEvery();**
} finally {
await session.endSession();
await client.close();
}
You can use session.abortTransaction() to abort a transaction so everything that happened already in the transaction will be rolled back.
See http://mongodb.github.io/node-mongodb-native/3.5/api/ClientSession.html#abortTransaction for the official docs.
See https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions for example code that uses abortTransaction().
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.