本文介绍了使用MongoDB Atlas时,mongo-go-driver因服务器选择超时而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
开始版本:1.12.5
Go Version: 1.12.5
我有这段代码使用了node.js mongo驱动程序
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();
});
哪个工作正常.
使用 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
我不在容器/泊坞窗中运行它.
I am not running this inside a container/docker.
推荐答案
我遇到了同样的问题,并且已经解决了.如果您有相同的问题,也许我的解决方案会为您提供帮助.尝试在mongo连接网址之后添加参数 connect = direct
.
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.
这篇关于使用MongoDB Atlas时,mongo-go-driver因服务器选择超时而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!