Middleware and Hooks¶
Goose supports schema-level middleware (pre/post hooks) that run before or after specific operations like Save, Update, Find, and Delete.
Pre and Post Hooks¶
You can define hooks directly on a schema using Pre and Post methods.
schema.Pre("Save", func(ctx context.Context, doc any) error {
// Perform operations before save
return nil
})
schema.Post("Save", func(ctx context.Context, doc any) error {
// Perform operations after save
return nil
})
Interface-Based Hooks¶
Alternatively, your model types can implement specific interfaces (e.g., HookSave) to automatically register hooks.
type User struct {
Name string
}
func (u *User) PreSave(ctx context.Context) error {
// Runs before saving the user
return nil
}
Supported Hooks
Goose supports a variety of operations for hooks including Save, Update, Find, FindOne, Delete, and DeleteOne.