首页 > 解决方案 > mongo.Connect() 在使用 mongo-go-driver 的 Go 中没有按预期工作

问题描述

我正在使用这个包:"github.com/mongodb/mongo-go-driver/mongo"

我正在尝试使用文档中指定的以下内容

mongoContext, _ := context.WithTimeout(context.Background(), 10*time.Second)
mongoClient, _ := mongo.Connect(mongoContext, "mongodb://localhost:27017")

但是在第二行我得到了错误:

cannot use "mongodb://localhost:27017" (type string) as type *options.ClientOptions in argument to mongo.Connect

似乎文档与实现不匹配。有人成功了吗?

该文档指出:

//To do this in a single step, you can use the Connect function:
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, "mongodb://localhost:27017")

标签: mongodbgo

解决方案


文档指出该Connect方法必须使用上下文对象。它还提供了一个使用示例:

您必须首先将连接字符串提供给NewClient函数。


client, err := mongo.NewClient(mongo.options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    // error
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
    // error
}

// here you can use the client object

https://godoc.org/github.com/mongodb/mongo-go-driver/mongo#Client.Connect

要将其用作您尝试执行的单个步骤,您应该能够执行以下操作:

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
mongoClient, err := mongo.Connect(ctx, mongo.options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    // error
}

(连接字符串必须放在 options.ClientOptions 对象中,该options.Client().ApplyURI()方法会处理它)


推荐阅读