mongodb 在 commitTransaction 失败后我需要一个 abortTransaction 吗?

标签 mongodb mongoose transactions commit rollback

mongoose/mongodb node.js代码:

session.commitTransaction(function(err, reply){
    if(err) {
       session.abortTransaction(); //Do I need this abort?
    }
}

有没有人可以帮助我。

最佳答案

查看 documentation关于事务的 mongodb 及其提供的示例。

您应该在数据库请求出现异常后使用 session.abortTransaction();

但在 commit 拒绝后就不需要了。


也就是说 mongoose没有 abortTransactions()。所以我想这不是必需的。


// Runs the txnFunc and retries if TransientTransactionError encountered

function runTransactionWithRetry(txnFunc, session) {
    while (true) {
        try {
            txnFunc(session);  // performs transaction
            break;
        } catch (error) {
            // If transient error, retry the whole transaction
            if ( error.hasOwnProperty("errorLabels") && error.errorLabels.includes("TransientTransactionError")  ) {
                print("TransientTransactionError, retrying transaction ...");
                continue;
            } else {
                throw error;
            }
        }
    }
}

// Retries commit if UnknownTransactionCommitResult encountered

function commitWithRetry(session) {
    while (true) {
        try {
            session.commitTransaction(); // Uses write concern set at transaction start.
            print("Transaction committed.");
            break;
        } catch (error) {
            // Can retry commit
            if (error.hasOwnProperty("errorLabels") && error.errorLabels.includes("UnknownTransactionCommitResult") ) {
                print("UnknownTransactionCommitResult, retrying commit operation ...");
                continue;
            } else {
                print("Error during commit ...");
                throw error;
            }
       }
    }
}

// Performs inserts and count in a transaction
function updateEmployeeInfo(session) {
   employeesCollection = session.getDatabase("hr").employees;
   eventsCollection = session.getDatabase("reporting").events;

   // Start a transaction for the session that uses:
   // - read concern "snapshot"
   // - write concern "majority"

   session.startTransaction( { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } } );

   try{
      eventsCollection.insertOne(
         { employee: 3, status: { new: "Active", old: null },  department: { new: "XYZ", old: null } }
      );

      // Count number of events for employee 3

      var countDoc = eventsCollection.aggregate( [ { $match:  { employee: 3 } }, { $count: "eventCounts" } ] ).next();

      print( "events count (in active transaction): " + countDoc.eventCounts );

      // The following operations should fail as an employee ``3`` already exist in employees collection
      employeesCollection.insertOne(
         { employee: 3, name: { title: "Miss", name: "Terri Bachs" }, status: "Active", department: "XYZ" }
      );
   } catch (error) {
      print("Caught exception during transaction, aborting.");
      session.abortTransaction();
      throw error;
   }

   commitWithRetry(session);

} // End of updateEmployeeInfo function

// Start a session.
session = db.getMongo().startSession( { mode: "primary" } );

try{
   runTransactionWithRetry(updateEmployeeInfo, session);
} catch (error) {
   // Do something with error
} finally {
   session.endSession();
}

关于mongodb 在 commitTransaction 失败后我需要一个 abortTransaction 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52090819/

相关文章:

php - 比特币钱包交易回调

mongodb - 在 MongoDB 中使用长字段名称时,有没有办法解决空间使用问题?

node.js - 如何在Nodejs中生成带有过期时间的登录代码?

javascript - 使用 Node 和 Mongo 时,Angular 无法识别模块

mongodb - 如何使用 MongoDB 的 Map/Reduce 对多个键进行分组?发出多个键?

javascript - 打印对象不包含所有键

node.js - 检查数组中是否存在所有元素

transactions - 在 Cassandra 中混合轻量级事务和正常写入

javascript - 使用多个 ObjectId 的 Mongoose 查询(带有 'ref' )

sql-server - 如何转换为 ADO.NET 事务而不是 SQL Server 事务?