Models¶
Models are the foundation of goose. They provide a type-safe interface to interact with your MongoDB collections. By leveraging Go 1.18+ Generics, goose.Model[T] ensures that the data you write to and read from the database strictly matches your Go struct definition.
Defining a Model¶
To create a model, use the goose.NewModel[T] function. It takes your database client, the collection name, and optionally, a schema.
package main
import (
"github.com/devsamahd/goose"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// User represents our document structure
type User struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Name string `bson:"name"`
Email string `bson:"email"`
}
func main() {
// Assume `client` is a connected goose.Database
schema := goose.NewSchema()
userModel := goose.NewModel[User](client, "users", schema)
}
Collection Name
If your Schema has the Collection option set via goose.WithCollection(), it will override the collection name provided to NewModel.
Accessing the Underlying Collection¶
If you need to bypass goose and execute raw mongo-driver operations, you can access the underlying *mongo.Collection.
Type Safety¶
Because goose uses generics, all CRUD operations and Query builders return your specific type *T or []*T. You no longer need to manually decode bson.M or type-assert interfaces!