I am trying to connect to a mongoDB instance locally from Go repo like so:
import (
"context"
"time"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"log"
)
var MongoClient *mongo.Client
func InitMongoDB() {
var err error
clientOptions := options.Client().ApplyURI(MongoDBURI)
MongoClient, err := mongo.Connect(clientOptions)
if err != nil {
log.Fatal(err)
}
err = MongoClient.Ping(context.TODO(), nil)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = MongoClient.Ping(ctx, nil) //readpref.Primary())
if err != nil {
log.Fatal("Could not ping MongoDB: ", err)
}
log.Printf("MongoDB connection established %s", MongoDBURI)
}
func GetMongoClient() *mongo.Client {
if MongoClient == nil {
log.Fatal("MongoDB client has not been initialized")
}
return MongoClient
}
From my main.go
function I am simply trying to list all databases after connecting:
func main(){
InitMongoDB()
defer func() {
if err = MongoClient.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll, err := GetMongoClient().ListDatabaseNames(context.TODO(), nil)
}
GetMongoClient()
here is throwing the error MongoDB client has not been initialized
because its the client object is nil
why is it nil? if the ping worked and no error was thrown during initialisation?