doushouxie7064 2019-05-13 12:06
浏览 275

使用MongoDB Atlas时,mongo-go-driver失败,服务器选择超时

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 自适应 AR 模型 参数估计Matlab程序
    • ¥100 角动量包络面如何用MATLAB绘制
    • ¥15 merge函数占用内存过大
    • ¥15 Revit2020下载问题
    • ¥15 使用EMD去噪处理RML2016数据集时候的原理
    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
    • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
    • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
    • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
    • ¥15 如何在炒股软件中,爬到我想看的日k线