4

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.

revant
  • 234
  • 3
  • 13
  • In order to use MongoDB multi-documents transactions you need a replica set. This is a duplicate to https://stackoverflow.com/questions/51461952/mongodb-v4-0-transaction-mongoerror-transaction-numbers-are-only-allowed-on-a – Wan B. Jun 03 '19 at 05:40
  • I had created a replica set. My issue was with the mongo go driver not able to connect to it properly. – revant Jun 05 '19 at 20:46
  • Could you provide the connection error message? because the error message that you posted (`IllegalOperation`) indicates that the deployment is not a replica set. – Wan B. Aug 16 '19 at 00:53
  • hey @revant, did u find out about this what's wrong? I really need know this so bad, I have same issue like you that can't connect, hope u can share the answer of this – Weq Iou Jun 13 '20 at 08:41

1 Answers1

0

This is an issue with your connection code - not your transaction implementation most likely. Try using the more modern connection string for connecting to a replica set:

connectionString := "mongodb+srv://USERNAME:PASSWORD@mongoatlas.1mxpg.mongodb.net/?retryWrites=true&w=majority"

var err error
Client, err = mongo.NewClient(options.Client().ApplyURI(ConnectionString))
if err != nil {
    log.Fatal(err)
}
fIwJlxSzApHEZIl
  • 11,861
  • 6
  • 62
  • 71