我正在学习使用Golang驱动程序go.mongodb.org/mongo-driver/mongo
进行MongoDB事务处理.我正沿着this SO answer号和this example on github号路行驶.
示例代码由@ siphix给出:
if session, err = client.StartSession(); err != nil {
t.Fatal(err)
}
if err = session.StartTransaction(); err != nil {
t.Fatal(err)
}
if err = mongo.WithSession(ctx, session, func(sc mongo.SessionContext) error {
if result, err = collection.UpdateOne(sc, bson.M{"_id": id}, update); err != nil {
t.Fatal(err)
}
if result.MatchedCount != 1 || result.ModifiedCount != 1 {
t.Fatal("replace failed, expected 1 but got", result.MatchedCount)
}
// more interrelated operations ...
if err = session.CommitTransaction(sc); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
session.EndSession(ctx)
在这两个示例中,它们都不会在出错的情况下回滚.我知道这是一个用于演示的样本.但当我在我的代码中执行同样的操作时,它工作得很好.
在出错的情况下省略回滚可以吗(驱动程序能处理吗)?还是我错过了什么?