首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用MongoDB地图集时,mongo-go-driver失败,服务器选择超时

使用MongoDB地图集时,mongo-go-driver失败,服务器选择超时
EN

Stack Overflow用户
提问于 2019-05-13 20:06:17
回答 1查看 2.8K关注 0票数 3

Go版本: 1.12.5

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

代码语言:javascript
复制
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,我做到了:

代码语言:javascript
复制
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)
}

但这种恐慌是这样的:

代码语言:javascript
复制
panic: server selection error: server selection timeout
current topology: Type: ReplicaSetNoPrimary

我不是在容器/docker中运行它。

EN

回答 1

Stack Overflow用户

发布于 2020-07-23 10:53:08

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56111999

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档