首页 > 解决方案 > MongoDB 控制的事务中止

问题描述

我与 golang 的 mongo 驱动程序一起工作,但对于其他实现来说,这个问题可能是实际的。

如果出现错误,mongo 驱动程序是否总是中止事务?我可以防止交易的隐式中止吗?

例如,对于这样的代码,我总是得到err2 = (NoSuchTransaction) Transaction 7 has been aborted.if err1!= nil

    client := ir.Source.Client()
    session, err := client.StartSession()
    if err != nil {
        return err
    }

    if err := session.StartTransaction(); err != nil {
        return err
    }
    if err = mongo.WithSession(ctx, session, func(sc mongo.SessionContext) error {

        _, err1 := ir.Source.Collection(collectionName).UpdateOne(sc,
            bson.D{{Key: "_id", Value: bid}},
            bson.M{
                "$set": bson.D{{Key: "name", Value: "Name"}},
            },
        )
        if err1 != nil {
            log.Println(err1) // I don`t want abort here
        }
        _, err2 = ir.Source.Collection("collectionName").UpdateOne(sc,
            bson.D{{Key: "_id", Value: bid}},
            bson.M{
                "$set": bson.D{{Key: "name", Value: "Name"}},
            },
        )
        if err2 != nil {
            log.Println(err2) 
            sc.AbortTransaction(sc) // i want abort only here
        }
        return sc.CommitTransaction(sc)
     }); err!=nil {
  return err
}

我可以使用一些选项进行交易或重写代码,以便我自己控制交易中止吗?

标签: mongodbtransactionsmongo-go

解决方案


推荐阅读