3

Go Version: 1.12.5

I have this code which uses the node.js mongo driver

const MongoClient = require('mongodb').MongoClient;
const uri = process.env.MONGO_HOST + "dbname?retryWrites=true";
const client = new MongoClient(uri, {
    useNewUrlParser: true
});

client.connect(async (err) => {
    if (err) {
        throw err
    }
    const collection = client.db("dbname").collection("collectionName");
    const cursor = collection.find()
    await cursor.forEach(console.log)
    // perform actions on the collection object
    client.close();
});

Which works fine.

Using the mongo-go-driver, I do:

client, err := mongo.NewClient(options.Client().ApplyURI(os.Getenv("MONGO_HOST") + "dbname?retryWrites=true")
if err != nil {
    panic(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
    panic(err)
}
database := client.Database("dbname")
collection := database.Collection("collectionName")

res, err := collection.Find(context.Background(), bson.M{}, &options.FindOptions{
    Sort: bson.M{
        "priority": -1,
    },
})
if err != nil {
    panic(err)
}
results := make([]structs.ResponseType, 0)
err = res.All(context.Background(), &results)
if err != nil {
    panic(err)
}

But this panics with:

panic: server selection error: server selection timeout
current topology: Type: ReplicaSetNoPrimary

I am not running this inside a container/docker.

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
  • The better question would be: why is there no primary in the cluster. The fact that npm eats anything and just does something is not surprising. – RickyA May 13 '19 at 12:17
  • I think the primary is discovered by the driver though, so it might be that the nodejs driver can find the primary but go can't. – Ayush Gupta May 13 '19 at 12:43
  • Which version of `mongo-go-driver`? also, what's the content of `MONGO_HOST` (Please just use template, don't post credentials. i.e. `mongodb://USER:PWD@server1.mongodb.net:27017` etc)? – Wan B. May 21 '19 at 00:21
  • @AyushGupta I was able to solve it when i added ca-certificates – pariola Sep 20 '19 at 18:37
  • @pariola in my case there was a bug in the mongo-go-driver 1.0.1, upgrading to 1.1.0 fixed it – Ayush Gupta Sep 20 '19 at 18:39
  • okay nice, i was experiencing this on docker with the scratch image. So adding the ca-certificates helped resolve that. Thanks – pariola Sep 20 '19 at 18:41

1 Answers1

2

I had the same problem and have solved it. If you have the same question, maybe my solution will help you. Try to add param connect=direct after your mongo connect url.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Sakura-by
  • 21
  • 2