Mongo-Go-Driver Failing to Connect

Peter Weyand picture Peter Weyand · Feb 20, 2019 · Viewed 8.7k times · Source

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?

Answer

Peter Weyand picture Peter Weyand · Feb 20, 2019

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.