Use mongodb connection from other function in Go?


(Illud) #1

I want to use mongodb connection from another function in golang example

func Conn(){
client, err := 
mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
 }

call that function.

func main(){
    Conn.client()//something like this
}

(Illud) #2

i resolved lke this

var CNX = Connection()
func Connection() *mongo.Client {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
          	log.Fatal(err)
    }

    // Check the connection
    err = client.Ping(context.TODO(), nil)

    if err != nil {
	    log.Fatal(err)
    }

    fmt.Println("Connected to MongoDB!")

    return client
}

//calll connection
 func main() {
      collection := db.CNX.Database("tasks").Collection("task")
 }

output "Connected to MongoDB!"

(Ashish Shekar) #3

That is one way of doing it, Another, is to use structs as your dependency injection tool.

Example:


type AppConnection struct {
  Client *mongo.Client
  IsConnected bool
  // and some other things that you need such as schemas etc..
}

func (ac AppConnection) Connect() {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
        ac.IsConnected = false
        return
    }

    // Check the connection
    err = client.Ping(context.TODO(), nil)

    if err != nil {
	    ac.IsConnected = false
        return
    }
    
    ac.IsConnected = true
    ac.Client = client

    fmt.Println("Connected to MongoDB!")
}

Now why this is good is you can pass around your pointer of AppConnection struct in other modules of your code without worrying about circular dependency while import.


(Illud) #4

Is not the same like this?

    var CNX = Connection()
    func Connection() *mongo.Client {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
      	log.Fatal(err)
   }

    // Check the connection
    err = client.Ping(context.TODO(), nil)

    if err != nil {
	    log.Fatal(err)
    }

    fmt.Println("Connected to MongoDB!")

    return client
}

//calll connection
 func main() {
      collection := db.CNX.Database("tasks").Collection("task")
 }