首页 > 解决方案 > mongo-go-driver 在使用 MongoDB Atlas 时因服务器选择超时而失败

问题描述

去版本:1.12.5

我有这个使用 node.js mongo 驱动程序的代码

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();
});

哪个工作正常。

使用mongo-go-driver,我这样做:

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)
}

但这会引起恐慌:

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

我没有在容器/docker 中运行它。

标签: node.jsmongodbgomongo-go

解决方案


我有同样的问题并且已经解决了。如果您有同样的问题,也许我的解决方案会对您有所帮助。尝试connect=direct在您的 mongo 连接 url 之后添加参数。


推荐阅读