dongxing8766 2019-05-29 19:33
浏览 897

无法使用mongo go驱动程序使用mongodb事务

I have created a mongodb replica set. I am able to run transactions from the mongo shell. But when I try to do it using mongo-go-driver I always get this error (IllegalOperation) Transaction numbers are only allowed on a replica set member or mongos. I am not sure where I am going wrong. I am using this as a reference https://github.com/simagix/mongo-go-examples/blob/master/examples/transaction_test.go.

I create the client like this

client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017,localhost:27018,localhost:27019?replicaSet=rs"))

I can connect to the individual mongodb instances, just not the replica set. This is the transaction that I am trying to run

var session mongo.Session

coll := db.Collection("collectionname")

if session, err = client.StartSession(); err != nil {
    return "", fmt.Errorf("Could not start session: %q", err)
}

if err = session.StartTransaction(); err != nil {
    return "", fmt.Errorf("Could not start Transaction: %q", err)
}

if err = mongo.WithSession(ctx, session, func(sc md.SessionContext) error {

    newVal, err = coll.InsertOne(sc, val) // some val that I have
    if err != nil {
        sc.AbortTransaction(sc)
        return fmt.Errorf("Error during New address creation, aborting: %q", err)
    }

    if err = sc.CommitTransaction(sc); err != nil {
        return fmt.Errorf("Error While commiting New address Transaction: %q", err)
    }
    return nil
}); err != nil {
    return "", err
}

session.EndSession(ctx)

Is there something I am missing. Is there some other example maybe that I can reference. Thanks for the help/suggestions.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 5037端口被adb自己占了
    • ¥15 Error in check.length("fill") : 'gpar'成分'fill'的长度不能为零
    • ¥15 python:excel数据写入多个对应word文档
    • ¥60 全一数分解素因子和素数循环节位数
    • ¥15 ffmpeg如何安装到虚拟环境
    • ¥188 寻找能做王者评分提取的
    • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
    • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
    • ¥15 写论文,需要数据支撑
    • ¥15 identifier of an instance of 类 was altered from xx to xx错误