database - Mongo-Go-Driver 连接失败
问题描述
所以我正在尝试使用https://github.com/mongodb/mongo-go-driver连接到 golang 中的 mongo 数据库。
这是我的连接处理程序:
var DB *mongo.Database
func CreateConnectionHandler()(*mongo.Database, error){
fmt.Println("inside createConnection in database package")
godotenv.Load()
fmt.Println("in CreateConnectionHandler and SERVER_CONFIG: ")
fmt.Println(os.Getenv("SERVER_CONFIG"))
uri:=""
if os.Getenv("SERVER_CONFIG")=="kubernetes"{
fmt.Println("inside kubernetes db config")
uri = "mongodb://patientplatypus:SUPERSECRETPASSDOOT@
mongo-release-mongodb.default.svc.cluster.local:27017/
platypusNEST?authMechanism=SCRAM-SHA-1"
}else if os.Getenv("SERVER_CONFIG")=="compose"{
fmt.Println("inside compose db config")
uri = "mongodb://datastore:27017"
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, uri)
if err != nil {
return nil, fmt.Errorf("mongo client couldn't connect: %v", err)
}
DB := client.Database("platypusNEST")
return DB, nil
}
我得到的错误是:
api | database/connection.go:29:30: cannot use uri (type
string) as type *options.ClientOptions in argument to mongo.Connect
所以我尝试用这样uri
的连接字符串替换:
client, err := mongo.Connect(ctx, "mongodb://datastore:27017")
但我仍然得到错误。
将此与文档中的内容进行比较:
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) client, err := mongo.Connect(ctx, "mongodb://localhost:27017")
而且完全一样!我真的不确定为什么会出现这个错误。有任何想法吗?
解决方案
对于那些来搜索的人 - 文档在这篇文章中已经过时了,但他们最新的推送在这里:https ://github.com/mongodb/mongo-go-driver/commit/32946b1f8b9412a6a94e68ff789575327bb257cf让他们通过连接执行此操作:
client, err := mongo.NewClient(options.Client().ApplyURI(uri))
您现在还需要导入选项包。快乐的黑客。
编辑:感谢 vcanales 找到这个 - 你是一位绅士和学者。
推荐阅读
- r - 使用循环标记 gt 表中的列
- c# - WPF:如何从 TextBox 获取当前绝对行号和列号(忽略文本换行)
- javascript - 如何在功能组件上接收 express 发送的数据?
- numpy - 如何在 Numpy 中逐行向量化乘法和重新加法?
- reactjs - 在 React 中重置表单并控制台记录服务器端的详细信息
- continuous-integration - Gitlab CI 使用规则启用合并结果
- reactjs - 无法获得 componentDidUpdate 内部方法的测试覆盖率
- .net - Yocto Linux 内核:如何将 .NET 核心框架构建到我的 Linux 映像中?
- flutter - 将变量转移到其他类
- java - 是否可以从 dto 和 User 类创建一个 newUser ?