Mongo-Go-Driver не может подключиться - PullRequest
0 голосов
/ 20 февраля 2019

Итак, я пытаюсь использовать https://github.com/mongodb/mongo-go-driver для подключения к базе данных mongo в golang.

Вот мой обработчик подключения:

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")

И это точно так же!Я действительно не уверен, почему есть эта ошибка.Есть идеи?

Ответы [ 2 ]

0 голосов
/ 27 июня 2019

В дополнение к принятому ответу - этот фрагмент ниже можно улучшить, используя переменную среды для передачи URL-адреса Mongodb.

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\n", err)
       return
   }

   fmt.Println("connected to nosql database:", mongoURL)

}


func main() {

   ConnectMongo()
}

Дополнительная информация о параметрах и readpref соответственно: https://docs.mongodb.com/manual/reference/method/cursor.readPref/index.html https://docs.mongodb.com/manual/core/read-preference/

0 голосов
/ 20 февраля 2019

Для тех, кто приходит на поиски - документы устарели на момент публикации, но их последний толчок здесь: https://github.com/mongodb/mongo-go-driver/commit/32946b1f8b9412a6a94e68ff789575327bb257cf заставляет их делать это с подключением:

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

ВыТакже теперь нужно будет импортировать пакет опций.Удачного взлома.

РЕДАКТИРОВАТЬ: спасибо vcanales за это - вы джентльмен и ученый.

...