Skip to content

Commit

Permalink
DOCS-13739: add defers to the code snippets in the README (mongodb#437)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Cho authored Jul 2, 2020
1 parent 20b6cab commit 3191cb1
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ To get started with the driver, import the `mongo` package, create a `mongo.Clie
import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)

client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
Expand All @@ -59,17 +60,29 @@ client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27
And connect it to your running MongoDB server:

```go
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = client.Connect(ctx)
```

To do this in a single step, you can use the `Connect` function:

```go
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
```

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

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

Calling `Connect` does not block for server discovery. If you wish to know if a MongoDB server has been found and connected to,
use the `Ping` method:

Expand Down

0 comments on commit 3191cb1

Please sign in to comment.