Mongo-Go-Driver无法连接

Pet*_*and 1 database database-connection go mongodb mongo-go

因此,我尝试使用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
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

api         | database/connection.go:29:30: cannot use uri (type 
string) as type *options.ClientOptions in argument to mongo.Connect
Run Code Online (Sandbox Code Playgroud)

所以我尝试用这样uri的连接字符串替换:

client, err := mongo.Connect(ctx, "mongodb://datastore:27017")
Run Code Online (Sandbox Code Playgroud)

但是我仍然遇到错误。

将此与文档中的内容进行比较:

ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, "mongodb://localhost:27017")
Run Code Online (Sandbox Code Playgroud)

它是完全一样的!我真的不确定为什么会出现此错误。有任何想法吗?

Pet*_*and 5

对于来此搜索的人-截至本文发布时,文档已过时,但此处的最新发布是:https : //github.com/mongodb/mongo-go-driver/commit/32946b1f8b9412a6a94e68ff789575327bb257cf要求他们使用连接进行此操作:

client, err := mongo.NewClient(options.Client().ApplyURI(uri))
Run Code Online (Sandbox Code Playgroud)

您现在还需要导入选项包。骇客入侵。

编辑:感谢vcanales找到了-您是一位绅士和学者。