我尝试使用 golang 驱动程序连接到 mongodb Atlas。
tlsConfig := &tls.Config{}
var mongoURI = "mongodb+srv://admin:password@prefix.mongodb.net:27017/dbname"
dialInfo, err := mgo.ParseURL(mongoURI)
if err != nil {
panic(err)
}
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
return conn, err
}
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
println("error")
log.Fatal(err)
}
_ = session
c := session.DB("Token").C("_Users")
user := &User{firstName: "username"}
err = c.Insert(user)
if err != nil {
println("error Again")
}
我没有收到未连接的错误。 我想知道可能是什么原因。 感谢您的帮助。
我尝试使用以下代码创建 DialInfo
dialInfo := &mgo.DialInfo{
Addrs: []string{"prefix.mongodb.net:27017"},
Database: "dbname",
Mechanism: "SCRAM",
Timeout: 10 * time.Second,
Username: "admin",
Password: "passwrd",
}
现在我无法访问服务器
最佳答案
I could only see that the code started, then nothing
如您所知,这是因为 DialInfo默认情况下有一个零超时。该调用将永远阻塞,等待建立连接。您还可以指定超时:
dialInfo.Timeout = time.Duration(30)
session, err := mgo.DialWithInfo(dialInfo)
Now I am getting no reachable servers
这是因为globalsign/mgo当前不支持 SRV connection string URI然而。参见 issues 112 . 您可以使用非 srv 连接 URI 格式 (MongoDB v3.4),请参阅相关问题 StackOverflow: 41173720 .
您可以使用 mongo-go-driver相反,如果您想使用 SRV 连接 URI 进行连接,例如:
mongoURI := "mongodb+srv://admin:password@prefix.mongodb.net/dbname?ssl=true&retryWrites=true"
client, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err = client.Connect(ctx)
defer client.Disconnect(ctx)
if err != nil {
log.Fatal(err)
}
database := client.Database("go")
collection := database.Collection("atlas")
上面的例子兼容当前版本v1.0.0
关于mongodb - 如何使用 mongodb 3.6 中的新 URL 从 golang 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52052311/