drz5553 2019-02-20 03:47
浏览 252
已采纳

Mongo-Go-Driver无法连接

So I am trying to use https://github.com/mongodb/mongo-go-driver to connect to a mongo database in golang.

Here is my connection handler:

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
}

And the error I am getting:

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

So I tried replacing uri with the connection string like this:

client, err := mongo.Connect(ctx, "mongodb://datastore:27017")

But I still got the error.

Compare this with what is in the documentation:

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

And it is exactly the same! I'm really not sure why there is this error. Any ideas?

  • 写回答

2条回答 默认 最新

  • douye1940 2019-02-20 04:24
    关注

    To those who come searching - the docs are out of date as of this posting, but their latest push here: https://github.com/mongodb/mongo-go-driver/commit/32946b1f8b9412a6a94e68ff789575327bb257cf has them doing this with the connect:

    client, err := mongo.NewClient(options.Client().ApplyURI(uri))
    

    You will also now need to import the options package. Happy hacking.

    EDIT: thanks vcanales for finding this - you're a gentleman and a scholar.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突