Schemas¶
While Go structs define the shape of your data, a Schema in goose defines the behavior, validation rules, hooks, and relationships of your data.
Creating a Schema¶
You can create an empty schema or one with explicit field definitions and options.
Schema Options¶
You can configure your schema using functional options:
schema := goose.NewSchema(
nil,
goose.WithTimestamps(true),
goose.WithCollection("custom_users_collection"),
goose.WithStrict(true),
)
Timestamps
WithTimestamps(true) tells goose to automatically manage createdAt and updatedAt fields when saving or updating documents.
Field Definitions¶
If you prefer defining rules in code rather than via struct tags, you can pass map[string]goose.FieldDef to NewSchema:
fields := map[string]goose.FieldDef{
"email": {
Type: goose.String,
Required: true,
Unique: true,
},
}
schema := goose.NewSchema(fields)
FieldDef Properties¶
The FieldDef struct provides extensive configuration for each field:
Required: Fails validation if the field is empty.Default: Sets a default value if missing.Unique: Ensures the value is unique across the collection.Ref: Specifies the target collection name for$lookuppopulation.Min/Max: Validation bounds for strings or numbers.Validate: A customgoose.ValidatorFn.Select: Defaults totrue; iffalse, the field is excluded from queries by default.