node.js - 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 中运行它。
解决方案
我有同样的问题并且已经解决了。如果您有同样的问题,也许我的解决方案会对您有所帮助。尝试connect=direct
在您的 mongo 连接 url 之后添加参数。
推荐阅读
- c - 二维阵列的一部分的无限循环工作
- api - 为什么 Flutter 应用安装“app-release.apk”时无法连接互联网?但它在调试模式下正常工作
- python - Kivy Action按钮无法通过python更新图标
- c++ - 为什么在我输入任何值之前打印此代码?
- java - 显示一年中最低的平均价格,以及该价格的周数,以及它发生的月份的名称
- python - 基于元数据从对象存储中检索对象
- perl - 哪个作业在哪个节点上运行?
- react-admin - 如何使用 ArrayInput 解析和格式化值转换道具
- python - 错误“utf-8”编解码器无法解码位置 268 中的字节 0x96:读取文件 csv 时的起始字节无效
- java - Android Studio View 的显示方式与我的手机(三星 Galaxy S5)不同