0

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

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

call that function.

func main(){
    Conn.client//something like this
}
Illud
  • 319
  • 1
  • 4
  • 12
  • Possible duplicate of [Referring to an open database connection inside a function](https://stackoverflow.com/questions/42581697/referring-to-an-open-database-connection-inside-a-function-golang), –  Nov 30 '19 at 20:09

1 Answers1

0

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

output "Connected to MongoDB!"
Illud
  • 319
  • 1
  • 4
  • 12