mongo-go-driver fails with Server Selection Timeout when using MongoDB Atlas

与世无争的帅哥 提交于 2020-01-15 03:18:10

问题


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.

来源:https://stackoverflow.com/questions/56111999/mongo-go-driver-fails-with-server-selection-timeout-when-using-mongodb-atlas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!