Documentation
¶
Index ¶
- Variables
- type AfterCreateHook
- type AfterDeleteHook
- type AfterFindHook
- type AfterSaveHook
- type AfterUpdateHook
- type AggregationCursor
- func (a *AggregationCursor[T]) AddFields(fields interface{}) *AggregationCursor[T]
- func (a *AggregationCursor[T]) Cursor() (*Cursor[T], error)
- func (a *AggregationCursor[T]) Exec() ([]*T, error)
- func (a *AggregationCursor[T]) Group(group interface{}) *AggregationCursor[T]
- func (a *AggregationCursor[T]) Limit(n int64) *AggregationCursor[T]
- func (a *AggregationCursor[T]) Lookup(lookup LookupStage) *AggregationCursor[T]
- func (a *AggregationCursor[T]) Match(filter interface{}) *AggregationCursor[T]
- func (a *AggregationCursor[T]) Project(projection interface{}) *AggregationCursor[T]
- func (a *AggregationCursor[T]) Skip(n int64) *AggregationCursor[T]
- func (a *AggregationCursor[T]) Sort(sort interface{}) *AggregationCursor[T]
- func (a *AggregationCursor[T]) Unwind(path string) *AggregationCursor[T]
- type BeforeCreateHook
- type BeforeDeleteHook
- type BeforeSaveHook
- type BeforeUpdateHook
- type Client
- type Cursor
- type Database
- type DeleteResult
- type DiscriminatorConfig
- type Document
- type FieldDef
- type FieldType
- type HookFunc
- type HookType
- type IndexDef
- type LookupStage
- type Model
- func (m *Model[T]) Aggregate(ctx context.Context, pipeline ...interface{}) *AggregationCursor[T]
- func (m *Model[T]) Collection() *mongo.Collection
- func (m *Model[T]) CountDocuments(ctx context.Context, filter interface{}) (int64, error)
- func (m *Model[T]) Create(ctx context.Context, doc *T) (*T, error)
- func (m *Model[T]) CreateIndex(ctx context.Context, index IndexDef) (string, error)
- func (m *Model[T]) CreateIndexes(ctx context.Context, indexes []IndexDef) ([]string, error)
- func (m *Model[T]) DeleteMany(ctx context.Context, filter interface{}) (*DeleteResult, error)
- func (m *Model[T]) DeleteOne(ctx context.Context, filter interface{}) (*DeleteResult, error)
- func (m *Model[T]) Distinct(ctx context.Context, field string, filter interface{}) ([]interface{}, error)
- func (m *Model[T]) DropIndex(ctx context.Context, name string) error
- func (m *Model[T]) Exists(ctx context.Context, filter interface{}) (bool, error)
- func (m *Model[T]) Find(ctx context.Context, filter ...interface{}) *Query[T]
- func (m *Model[T]) FindByID(ctx context.Context, id interface{}) *Query[T]
- func (m *Model[T]) FindByIDAndDelete(ctx context.Context, id interface{}) (*T, error)
- func (m *Model[T]) FindByIDAndUpdate(ctx context.Context, id, update interface{}) (*T, error)
- func (m *Model[T]) FindOne(ctx context.Context, filter interface{}) *Query[T]
- func (m *Model[T]) FindOneAndDelete(ctx context.Context, filter interface{}) (*T, error)
- func (m *Model[T]) FindOneAndUpdate(ctx context.Context, filter, update interface{}) (*T, error)
- func (m *Model[T]) InsertMany(ctx context.Context, docs []*T) ([]*T, error)
- func (m *Model[T]) ReplaceOne(ctx context.Context, filter interface{}, replacement *T) (*UpdateResult, error)
- func (m *Model[T]) UpdateMany(ctx context.Context, filter, update interface{}) (*UpdateResult, error)
- func (m *Model[T]) UpdateOne(ctx context.Context, filter, update interface{}) (*UpdateResult, error)
- type Option
- type Plugin
- type PopulateOption
- type Query
- func (q *Query[T]) All() ([]*T, error)
- func (q *Query[T]) Count() (int64, error)
- func (q *Query[T]) Cursor() (*Cursor[T], error)
- func (q *Query[T]) Exec() (*T, error)
- func (q *Query[T]) Lean() *Query[T]
- func (q *Query[T]) Limit(n int64) *Query[T]
- func (q *Query[T]) Populate(fields ...string) *Query[T]
- func (q *Query[T]) Select(fields ...string) *Query[T]
- func (q *Query[T]) Skip(n int64) *Query[T]
- func (q *Query[T]) Sort(field string, order int) *Query[T]
- func (q *Query[T]) SortBy(sorts bson.D) *Query[T]
- type Schema
- func (s *Schema) AddIndex(index IndexDef) *Schema
- func (s *Schema) AddVirtual(name string, def VirtualDef) *Schema
- func (s *Schema) ApplyVirtuals(doc interface{}) map[string]interface{}
- func (s *Schema) GetVirtual(name string, doc interface{}) (interface{}, bool)
- func (s *Schema) Post(hook HookType, fn HookFunc) *Schema
- func (s *Schema) Pre(hook HookType, fn HookFunc) *Schema
- func (s *Schema) SetVirtual(name string, doc interface{}, val interface{}) bool
- func (s *Schema) Use(plugin Plugin, opts ...interface{}) *Schema
- type SchemaOption
- type SchemaOptions
- type UpdateResult
- type ValidationError
- type ValidationErrors
- type ValidatorFn
- type VirtualDef
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotFound = errors.New("goose: document not found") ErrValidation = errors.New("goose: validation failed") ErrDuplicateKey = errors.New("goose: duplicate key") ErrInvalidID = errors.New("goose: invalid ObjectID") ErrNotConnected = errors.New("goose: not connected to MongoDB") ErrInvalidModel = errors.New("goose: model must be a pointer to a struct") ErrTransaction = errors.New("goose: transaction failed") ErrEmptyUpdate = errors.New("goose: update document is empty") )
Sentinel errors
Functions ¶
This section is empty.
Types ¶
type AfterCreateHook ¶
AfterCreateHook is called after inserting a new document.
type AfterDeleteHook ¶
AfterDeleteHook is called after a delete operation.
type AfterFindHook ¶
AfterFindHook is called after a document is decoded from a query.
type AfterSaveHook ¶
AfterSaveHook is called after any create or update.
type AfterUpdateHook ¶
AfterUpdateHook is called after an update operation.
type AggregationCursor ¶
type AggregationCursor[T any] struct { // contains filtered or unexported fields }
AggregationCursor is a chainable aggregation pipeline builder.
func (*AggregationCursor[T]) AddFields ¶
func (a *AggregationCursor[T]) AddFields(fields interface{}) *AggregationCursor[T]
AddFields adds an $addFields stage.
func (*AggregationCursor[T]) Cursor ¶
func (a *AggregationCursor[T]) Cursor() (*Cursor[T], error)
Cursor returns a type-safe cursor for the aggregation results.
func (*AggregationCursor[T]) Exec ¶
func (a *AggregationCursor[T]) Exec() ([]*T, error)
Exec executes the aggregation pipeline and returns all results.
func (*AggregationCursor[T]) Group ¶
func (a *AggregationCursor[T]) Group(group interface{}) *AggregationCursor[T]
Group adds a $group stage.
func (*AggregationCursor[T]) Limit ¶
func (a *AggregationCursor[T]) Limit(n int64) *AggregationCursor[T]
Limit adds a $limit stage.
func (*AggregationCursor[T]) Lookup ¶
func (a *AggregationCursor[T]) Lookup(lookup LookupStage) *AggregationCursor[T]
Lookup adds a $lookup stage.
func (*AggregationCursor[T]) Match ¶
func (a *AggregationCursor[T]) Match(filter interface{}) *AggregationCursor[T]
Match adds a $match stage.
func (*AggregationCursor[T]) Project ¶
func (a *AggregationCursor[T]) Project(projection interface{}) *AggregationCursor[T]
Project adds a $project stage.
func (*AggregationCursor[T]) Skip ¶
func (a *AggregationCursor[T]) Skip(n int64) *AggregationCursor[T]
Skip adds a $skip stage.
func (*AggregationCursor[T]) Sort ¶
func (a *AggregationCursor[T]) Sort(sort interface{}) *AggregationCursor[T]
Sort adds a $sort stage.
func (*AggregationCursor[T]) Unwind ¶
func (a *AggregationCursor[T]) Unwind(path string) *AggregationCursor[T]
Unwind adds an $unwind stage.
type BeforeCreateHook ¶
BeforeCreateHook is called before inserting a new document.
type BeforeDeleteHook ¶
BeforeDeleteHook is called before a delete operation.
type BeforeSaveHook ¶
BeforeSaveHook is called before any create or update.
type BeforeUpdateHook ¶
BeforeUpdateHook is called before an update operation.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client holds the MongoDB connection.
func Connect ¶
Connect establishes a connection to MongoDB. Use functional options to configure the connection.
Example:
client, err := goose.Connect(ctx, "mongodb://localhost:27017",
goose.WithDatabase("myapp"),
goose.WithTimeout(10 * time.Second),
)
func (*Client) DefaultDatabase ¶
DefaultDatabase returns a handle to the database configured via WithDatabase. Panics if no default database was configured.
func (*Client) Disconnect ¶
Disconnect closes the MongoDB connection.
func (*Client) MongoClient ¶
MongoClient returns the underlying mongo.Client for advanced usage.
func (*Client) WithTransaction ¶
WithTransaction executes fn within a MongoDB transaction. It automatically starts a session, begins a transaction, and: - Commits on success - Aborts on error - Handles transient transaction errors with retry
Example:
err := client.WithTransaction(ctx, func(sessCtx context.Context) error {
_, err := orderModel.Create(sessCtx, &order)
if err != nil { return err }
_, err = inventoryModel.UpdateOne(sessCtx,
bson.M{"_id": productID},
bson.M{"$inc": bson.M{"stock": -1}},
)
return err
})
type Cursor ¶
type Cursor[T any] struct { // contains filtered or unexported fields }
Cursor wraps a mongo.Cursor with type-safe decoding.
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database represents a MongoDB database.
func (*Database) MongoDatabase ¶
MongoDatabase returns the underlying mongo.Database for advanced usage.
type DeleteResult ¶
type DeleteResult struct {
DeletedCount int64
}
DeleteResult holds the result of a delete operation.
type DiscriminatorConfig ¶
type DiscriminatorConfig struct {
// Name is the discriminator value used to distinguish document types.
Name string
// Schema is the additional schema fields for this discriminator.
Schema *Schema
}
DiscriminatorConfig holds configuration for a discriminator model.
type Document ¶
type Document struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"_id"`
CreatedAt time.Time `bson:"createdAt,omitempty" json:"createdAt"`
UpdatedAt time.Time `bson:"updatedAt,omitempty" json:"updatedAt"`
}
Document provides standard MongoDB document fields. Embed this in your structs to get automatic _id and timestamp management.
Example:
type User struct {
goose.Document `bson:",inline"`
Name string `bson:"name" json:"name"`
Email string `bson:"email" json:"email"`
}
type FieldDef ¶
type FieldDef struct {
Type FieldType
Required bool
Default interface{}
Unique bool
Index bool
Ref string // Collection name for population
Enum []interface{}
Min interface{} // Min value or length
Max interface{} // Max value or length
Match string // Regex pattern for strings
Validate ValidatorFn // Custom validator
LocalField string // For populate virtuals
ForeignField string // For populate virtuals
JustOne bool // Single vs array for populate
Select *bool // Include by default in queries (nil = true)
Immutable bool // Cannot be changed after creation
Sparse bool // Sparse index
Trim bool // Auto-trim whitespace (strings)
Lowercase bool // Auto-lowercase (strings)
Uppercase bool // Auto-uppercase (strings)
}
FieldDef defines a single field in the schema.
type IndexDef ¶
type IndexDef struct {
Keys interface{} // bson.D for index keys
Name string
Unique bool
Sparse bool
ExpireAfterSeconds *int32
}
IndexDef defines a MongoDB index.
type LookupStage ¶
LookupStage defines a $lookup aggregation stage.
type Model ¶
type Model[T any] struct { // contains filtered or unexported fields }
Model provides type-safe CRUD operations for a MongoDB collection.
func (*Model[T]) Aggregate ¶
func (m *Model[T]) Aggregate(ctx context.Context, pipeline ...interface{}) *AggregationCursor[T]
Aggregate starts an aggregation pipeline.
func (*Model[T]) Collection ¶
func (m *Model[T]) Collection() *mongo.Collection
Collection returns the underlying mongo.Collection.
func (*Model[T]) CountDocuments ¶
CountDocuments counts documents matching the filter.
func (*Model[T]) CreateIndex ¶
CreateIndex creates a single index on the collection.
func (*Model[T]) CreateIndexes ¶
CreateIndexes creates multiple indexes on the collection.
func (*Model[T]) DeleteMany ¶
func (m *Model[T]) DeleteMany(ctx context.Context, filter interface{}) (*DeleteResult, error)
DeleteMany deletes all documents matching the filter.
func (*Model[T]) DeleteOne ¶
func (m *Model[T]) DeleteOne(ctx context.Context, filter interface{}) (*DeleteResult, error)
DeleteOne deletes a single document matching the filter.
func (*Model[T]) Distinct ¶
func (m *Model[T]) Distinct(ctx context.Context, field string, filter interface{}) ([]interface{}, error)
Distinct returns distinct values for the given field.
func (*Model[T]) FindByIDAndDelete ¶
FindByIDAndDelete finds a document by ID, deletes it, and returns it.
func (*Model[T]) FindByIDAndUpdate ¶
FindByIDAndUpdate finds a document by ID, updates it, and returns the updated document.
func (*Model[T]) FindOneAndDelete ¶
FindOneAndDelete finds a document, deletes it, and returns the deleted document.
func (*Model[T]) FindOneAndUpdate ¶
FindOneAndUpdate finds a document, updates it, and returns the updated document.
func (*Model[T]) InsertMany ¶
InsertMany inserts multiple documents.
func (*Model[T]) ReplaceOne ¶
func (m *Model[T]) ReplaceOne(ctx context.Context, filter interface{}, replacement *T) (*UpdateResult, error)
ReplaceOne replaces a single document matching the filter.
func (*Model[T]) UpdateMany ¶
func (m *Model[T]) UpdateMany(ctx context.Context, filter, update interface{}) (*UpdateResult, error)
UpdateMany updates all documents matching the filter.
type Option ¶
type Option func(*config)
Option configures a Client.
func WithDatabase ¶
WithDatabase sets the default database name.
func WithMaxPoolSize ¶
WithMaxPoolSize sets the maximum connection pool size.
func WithMinPoolSize ¶
WithMinPoolSize sets the minimum connection pool size.
func WithTimeout ¶
WithTimeout sets the connection/operation timeout.
type Plugin ¶
type Plugin func(schema *Schema, opts interface{})
Plugin is a function that extends a schema with additional behavior. Plugins can add fields, hooks, methods, virtuals, or indexes to a schema.
Example:
// Soft delete plugin
func SoftDeletePlugin(s *goose.Schema, opts interface{}) {
s.Pre(goose.HookDeleteOne, func(ctx context.Context, doc interface{}) error {
// Convert delete to soft delete
return nil
})
}
type PopulateOption ¶
type PopulateOption struct {
Path string // Field path to populate
Model string // Target collection (auto-inferred from schema Ref if omitted)
Select []string // Fields to include from populated doc
Match interface{} // Additional filter for populated docs
Populate []PopulateOption // Nested population
}
PopulateOption configures a population (join) operation.
type Query ¶
type Query[T any] struct { // contains filtered or unexported fields }
Query is a chainable, immutable query builder.
type Schema ¶
type Schema struct {
Fields map[string]FieldDef
Options SchemaOptions
Virtuals map[string]VirtualDef
PreHooks map[HookType][]HookFunc
PostHooks map[HookType][]HookFunc
Indexes []IndexDef
Plugins []pluginEntry
}
Schema defines the structure, validation rules, and behavior of a model.
func MergeSchemas ¶
MergeSchemas creates a new schema by merging a parent schema with a child schema. The child schema's fields are added to/override the parent's fields. Both schemas' hooks, virtuals, and plugins are combined.
func NewSchema ¶
func NewSchema(fields map[string]FieldDef, opts ...SchemaOption) *Schema
NewSchema creates a new Schema with the given field definitions and options.
func (*Schema) AddIndex ¶
AddIndex adds an index definition to the schema. Returns the schema for chaining.
func (*Schema) AddVirtual ¶
func (s *Schema) AddVirtual(name string, def VirtualDef) *Schema
AddVirtual registers a virtual field on the schema. Virtual fields are computed on read and are not stored in MongoDB.
Example:
schema.AddVirtual("fullName", goose.VirtualDef{
Get: func(doc interface{}) interface{} {
u := doc.(*User)
return u.FirstName + " " + u.LastName
},
})
func (*Schema) ApplyVirtuals ¶
ApplyVirtuals computes all virtual fields for a document and returns them as a map.
func (*Schema) GetVirtual ¶
GetVirtual retrieves a virtual field value for the given document.
func (*Schema) SetVirtual ¶
SetVirtual sets a virtual field value on the given document.
type SchemaOption ¶
type SchemaOption func(*SchemaOptions)
SchemaOption configures schema creation.
func WithCollection ¶
func WithCollection(name string) SchemaOption
WithCollection sets a custom collection name for the schema.
func WithDiscriminatorKey ¶
func WithDiscriminatorKey(key string) SchemaOption
WithDiscriminatorKey sets the discriminator key for schema inheritance.
func WithStrict ¶
func WithStrict(b bool) SchemaOption
WithStrict configures strict mode, whether to reject fields not defined in the schema.
func WithTimestamps ¶
func WithTimestamps(b bool) SchemaOption
WithTimestamps configures whether to auto-manage createdAt/updatedAt timestamps.
func WithVersionKey ¶
func WithVersionKey(b bool) SchemaOption
WithVersionKey configures whether to use the __v versioning key.
type SchemaOptions ¶
type SchemaOptions struct {
Timestamps bool // Auto-manage createdAt/updatedAt
Collection string // Override collection name
DiscriminatorKey string // Discriminator key for inheritance
Strict bool // Reject fields not in schema (default: true)
VersionKey bool // Enable __v versioning
}
SchemaOptions configures schema-level behavior.
type UpdateResult ¶
type UpdateResult struct {
MatchedCount int64
ModifiedCount int64
UpsertedCount int64
UpsertedID interface{}
}
UpdateResult holds the result of an update operation.
type ValidationError ¶
type ValidationError struct {
Field string
Message string
Value interface{}
Kind string // "required", "min", "max", "enum", "match", "custom"
}
ValidationError represents a single field validation failure.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error returns the error message.
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error
Unwrap allows standard errors.Is/As to work with ErrValidation.
type ValidationErrors ¶
type ValidationErrors struct {
Errors []ValidationError
}
ValidationErrors aggregates multiple validation failures.
func (*ValidationErrors) Error ¶
func (e *ValidationErrors) Error() string
Error returns a joined string of all validation errors.
func (*ValidationErrors) Unwrap ¶
func (e *ValidationErrors) Unwrap() error
Unwrap allows standard errors.Is/As to work with ErrValidation.
type ValidatorFn ¶
type ValidatorFn func(value interface{}) error
ValidatorFn is a function that validates a value. It should return nil if the value is valid, or an error describing the failure.
func Enum ¶
func Enum(values ...interface{}) ValidatorFn
Enum returns a validator that checks if value is in the allowed set.
func Match ¶
func Match(pattern string) ValidatorFn
Match returns a validator that checks if a string matches a regex pattern.
func MaxLength ¶
func MaxLength(n int) ValidatorFn
MaxLength returns a validator for maximum string length.
func MinLength ¶
func MinLength(n int) ValidatorFn
MinLength returns a validator for minimum string length.
func Required ¶
func Required(fieldName string) ValidatorFn
Required returns a validator that checks a value is non-zero/non-nil/non-empty.
type VirtualDef ¶
type VirtualDef struct {
// Get computes the virtual field value from the document.
Get func(doc interface{}) interface{}
// Set applies a value to the document (optional).
Set func(doc interface{}, val interface{})
}
VirtualDef defines a virtual (computed) field that is not persisted to MongoDB.