Home > OS >  When mongodb client should disconnect after instantiating client?
When mongodb client should disconnect after instantiating client?

Time:08-15

As per the documentation in Readme:

Make sure to defer a call to Disconnect after instantiating your client:

defer func() {
    if err = client.Disconnect(ctx); err != nil {
        panic(err)
    }
}()

Does the above documentation meant to disconnect, during shutdown of the program(using mongodb driver)?

CodePudding user response:

They just reminded you that you should always close the connection to the database at some point. When exactly is up to you. Usually, you initialize the database connection at the top-level of your application, so the defer call should be at the same level. For example,

func main() {
 client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
 
  defer func() {
    if err = client.Disconnect(ctx); err != nil {
        panic(err)
    }
  }()

 // Pass the connection to other components of your appliaction
 doSomeWork(client)
}

Note: If you are using Goroutines don't forget to synchronize them in main otherwise the connection will be close too early.

CodePudding user response:

I think the documentation meant to use defer with client.Disconnect in the main function of your program. Thanks to that your program will close all the MongoDB client connections before exiting.

If you would use it e.g. in a helper function that prepares that client, it would close all the connections right after the client creation which may not be something you want.

  • Related