mongodb - 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")
解决方案
文档指出该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()
方法会处理它)
推荐阅读
- c++ - 与余数运算符等效的操作,用于处理低于允许的最小值的值
- coq - 如何在coq中制作反函数
- windows - 在 Powershell 中使用批处理式环境变量解释字符串
- cadence-workflow - 如果子工作流方法抛出异常,Java 客户端使用 Async.function 调用子工作流无法编译
- azure-devops - 如何将 Mark Down 样式添加到 Azure DevOps 网站
- http - 未处理的异常:在收到完整标头之前连接关闭无法解决此问题
- javascript - 将每个索引保存到每个按钮中
- html - 如何在没有模板引擎的情况下使用 NodeJS 在 HTML 中呈现动态内容
- firebase - 使用 firestore 上的实时更改侦听器更新 VueJS 上的列表
- css - 从 CSS 模块导入属性选择器