Skip to content

Configuration

Connecting to MongoDB efficiently is a critical part of your application. Goose leverages Go's functional options pattern to make configuration clean, safe, and easily extensible.

Connecting to MongoDB

The entry point for configuration is the goose.Connect function. It requires a context.Context and a MongoDB URI, followed by optional configuration functions.

package main

import (
    "context"
    "log"
    "time"

    "github.com/devsamahd/goose"
)

func main() {
    ctx := context.Background()

    client, err := goose.Connect(ctx, "mongodb://localhost:27017",
        goose.WithDatabase("myapp_db"),
        goose.WithTimeout(10 * time.Second),
        goose.WithMaxPoolSize(100),
        goose.WithMinPoolSize(10),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer client.Disconnect(ctx)
}

Connection Options

Here is the list of functional options you can pass to goose.Connect:

WithDatabase(name string)

Sets the default database for your Goose client. When you initialize models or call client.DefaultDatabase(), Goose will use this database.

goose.WithDatabase("production_db")

WithTimeout(d time.Duration)

Sets the connection timeout for the underlying MongoDB driver. This prevents your application from hanging indefinitely if the database is unreachable.

goose.WithTimeout(5 * time.Second) // default is 10 seconds

WithMaxPoolSize(size uint64)

Configures the maximum number of connections the driver will maintain in its connection pool. This is useful for high-concurrency environments.

goose.WithMaxPoolSize(200) // default is 100

WithMinPoolSize(size uint64)

Sets the minimum number of idle connections the driver keeps open. This can help reduce latency during sudden spikes in traffic.

goose.WithMinPoolSize(10) // default is 0

Advanced Database Access

While Goose models hide most of the boilerplate, sometimes you need direct access to the database or the underlying mongo.Client.

Accessing the Default Database

If you configured WithDatabase, you can easily retrieve a handle to it:

db := client.DefaultDatabase()

Panic Risk

If you call client.DefaultDatabase() without having configured WithDatabase during connection, Goose will panic. Always ensure you've set a default database if you rely on this method.

Accessing Specific Databases

You can connect to a specific database on the fly, which is useful for multi-tenant applications:

tenantDB := client.Database("tenant_12345")

Accessing the Driver Directly

For operations not currently covered by Goose's ODM layers, you can drop down to the official go.mongodb.org/mongo-driver:

mongoClient := client.MongoClient()
mongoDB := db.MongoDatabase()