Use mongodb connection from other function in Go?

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
}

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

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.

1 Like

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.