本文介绍了如何使用MongoDB 3.6中的新URL从Golang连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用golang驱动程序连接到mongodb Atlas.

I tried to connect to mongodb Atlas using golang drivers.

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

我没有收到未连接的错误消息.我想知道可能是什么原因.感谢您的帮助.

I am not getting an error not getting connected.I am wondering what could be the reason.'Any help is appreciated.

我尝试使用以下代码创建DialInfo

I tried to create DialInfo using below code

    dialInfo := &mgo.DialInfo{
    Addrs:     []string{"prefix.mongodb.net:27017"},
    Database:  "dbname",
    Mechanism: "SCRAM",
    Timeout:   10 * time.Second,
    Username:  "admin",
    Password:  "passwrd",
}

现在我没有可访问的服务器

Now I am getting no reachable servers

推荐答案

您已经发现,这是因为默认情况下 DialInfo 具有零超时.该呼叫将永远阻止等待建立连接.您还可以通过以下方式指定超时:

As you have figured out, this is because DialInfo by default has a zero timeout. The call will block forever waiting for a connection to be established. You can also specify a timeout with:

dialInfo.Timeout = time.Duration(30)
session, err := mgo.DialWithInfo(dialInfo)

这是因为 globalsign/mgo 当前不支持SRV 连接字符串URI 至今.参见问题112 .您可以使用非srv连接URI格式(MongoDB v3.4),请参阅相关问题.

This is because globalsign/mgo does not currently support SRV connection string URI yet. See issues 112.You can use the non-srv connection URI format (MongoDB v3.4), see a related question StackOverflow: 41173720.

您可以改用 mongo-go-driver 如果您想使用SRV连接URI进行连接,例如:

You can use mongo-go-driver instead if you would like to connect using the SRV connection URI, for example:

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兼容

The above example is compatible with the current version v1.0.0

这篇关于如何使用MongoDB 3.6中的新URL从Golang连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:36