drz5553
2019-02-20 03:47
浏览 230

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?

图片转代码服务由CSDN问答提供 功能建议

所以我正在尝试使用 https://github.com/mongodb/mongo-go-driver 连接到golang中的mongo数据库。

此处 是我的连接处理程序:

  var DB * mongo.Database 
 
func CreateConnectionHandler()(* mongo.Database,error){
 fmt.Println(“ inside createConnection 在数据库包中“)
 godotenv.Load()
 fmt.Println(”在CreateConnectionHandler和SERVER_CONFIG中:“)
 fmt.Println(os.Getenv(” SERVER_CONFIG“))
 uri:=”“ 
 如果os.Getenv(“ SERVER_CONFIG”)==“ kubernetes” {
 fmt.Println(“ in kubernetes db config”)
 uri =“ mongodb:// Patientplatypus:SUPERSECRETPASSDOOT @ 
 mongo-release-mongodb.default  .svc.cluster.local:27017 / 
 platypusNEST?authMechanism = SCRAM-SHA-1“ 
}否则,如果os.Getenv(” SERVER_CONFIG“)==” compose“ {
 fmt.Println(”在撰写数据库中 config“)
 uri =  “ mongodb:// datastore:27017” 
} 
 ctx,_:= context.WithTimeout(context.Background(),10 * time.Second)
客户端,err:= mongo.Connect(ctx,uri)  
如果err!= nil {
返回nil,fmt.Errorf(“ mongo客户端无法连接:%v”,err)
} 
 DB:= client.Database(“ platypusNEST”)
返回 DB,nil 
} 
   
 
 

和我得到的错误:

  api |  database / connection.go:29:30:无法在mongo.Connect参数中使用uri(
string类型)作为类型* options.ClientOptions.Connect 
   
 
 

用以下连接字符串替换 uri

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

但是我仍然收到错误消息。

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

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

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duan198727 2019-06-27 14:53

    In addition to the accepted answer - this snippet below may be improved by using an environment variable to pass in the Mongodb URL.

    package main
    
    import (
       "context
       "fmt"
       "time"
       "go.mongodb.org/mongo-driver/mongo"
       "go.mongodb.org/mongo-driver/mongo/options"
       "go.mongodb.org/mongo-driver/mongo/readpref"
    )
    
    func ConnectMongo() {
    
       var (
           client     *mongo.Client
           mongoURL = "mongodb://localhost:27017"
       )
    
       // Initialize a new mongo client with options
       client, err := mongo.NewClient(options.Client().ApplyURI(mongoURL))
    
       // Connect the mongo client to the MongoDB server
       ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
       err = client.Connect(ctx)
    
       // Ping MongoDB
       ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
       if err = client.Ping(ctx, readpref.Primary()); err != nil {
           fmt.Println("could not ping to mongo db service: %v
    ", err)
           return
       }
    
       fmt.Println("connected to nosql database:", mongoURL)
    
    }
    
    
    func main() {
    
       ConnectMongo()
    }
    

    More information on options and readpref respectively: https://docs.mongodb.com/manual/reference/method/cursor.readPref/index.html https://docs.mongodb.com/manual/core/read-preference/

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题