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.

6
  • 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. Commented May 13, 2019 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. Commented May 13, 2019 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:[email protected]:27017 etc)? Commented May 21, 2019 at 0:21
  • @AyushGupta I was able to solve it when i added ca-certificates Commented Sep 20, 2019 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 Commented Sep 20, 2019 at 18:39

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.