Records are instances of collection data. They represent individual rows in your database tables and provide methods for data manipulation.
Creating records
NewRecord()
Create a new empty record for a collection:
collection, _ := app.FindCollectionByNameOrId("posts")
record := core.NewRecord(collection)
Setting field values
record.Set("title", "My First Post")
record.Set("content", "This is the content")
record.Set("views", 0)
record.Set("published", true)
Bulk loading data
data := map[string]any{
"title": "My Post",
"content": "Content here",
"views": 100,
}
record.Load(data)
Saving records
if err := app.Save(record); err != nil {
log.Fatal(err)
}
Finding records
FindRecordById()
Find a record by its ID:
record, err := app.FindRecordById("posts", "RECORD_ID")
if err != nil {
log.Fatal(err)
}
FindFirstRecordByData()
Find the first record matching a key-value pair:
record, err := app.FindFirstRecordByData("users", "email", "test@example.com")
if err != nil {
log.Fatal(err)
}
FindFirstRecordByFilter()
Find the first record matching a filter:
record, err := app.FindFirstRecordByFilter(
"posts",
"title ~ 'tutorial' && published = true",
)
if err != nil {
log.Fatal(err)
}
FindRecordsByFilter()
Find multiple records with filtering, sorting, and pagination:
records, err := app.FindRecordsByFilter(
"posts",
"published = true", // filter
"-created", // sort (descending by created)
10, // limit
0, // offset
)
if err != nil {
log.Fatal(err)
}
FindRecordsByIds()
Find multiple records by their IDs:
ids := []string{"id1", "id2", "id3"}
records, err := app.FindRecordsByIds("posts", ids)
if err != nil {
log.Fatal(err)
}
FindAllRecords()
Find all records matching optional expressions:
import "github.com/pocketbase/dbx"
// All records
allRecords, err := app.FindAllRecords("posts")
// With filter expressions
records, err := app.FindAllRecords(
"posts",
dbx.HashExp{"published": true},
)
Getting field values
Type-safe getters
title := record.GetString("title")
views := record.GetInt("views")
published := record.GetBool("published")
rating := record.GetFloat("rating")
created := record.GetDateTime("created")
tags := record.GetStringSlice("tags")
Generic Get()
Get a value as any type:
value := record.Get("fieldName")
GetRaw()
Get the raw, unnormalized value:
rawValue := record.GetRaw("fieldName")
Updating records
Update and save
record, err := app.FindRecordById("posts", "RECORD_ID")
if err != nil {
log.Fatal(err)
}
record.Set("views", record.GetInt("views") + 1)
if err := app.Save(record); err != nil {
log.Fatal(err)
}
Field modifiers
Use modifiers to perform operations on numeric and array fields:
// Increment a number field
record.Set("views+", 1)
// Decrement a number field
record.Set("score-", 5)
// Append to an array field
record.Set("tags+", "golang")
// Remove from an array field
record.Set("tags-", "deprecated")
ReplaceModifiers()
Manually apply modifiers to data:
data := map[string]any{
"views+": 10,
"score-": 5,
}
newData := record.ReplaceModifiers(data)
// newData["views"] will be the original value + 10
// newData["score"] will be the original value - 5
Deleting records
Delete a record
record, err := app.FindRecordById("posts", "RECORD_ID")
if err != nil {
log.Fatal(err)
}
if err := app.Delete(record); err != nil {
log.Fatal(err)
}
Truncate a collection
Delete all records in a collection:
collection, _ := app.FindCollectionByNameOrId("posts")
if err := app.TruncateCollection(collection); err != nil {
log.Fatal(err)
}
Truncating a collection deletes all records and triggers cascade actions. This operation cannot be undone.
Working with files
Getting uploaded files
Access files that are being uploaded with the record:
files := record.GetUnsavedFiles("documents")
for _, file := range files {
log.Printf("File: %s (%d bytes)", file.Name, file.Size)
// Modify file name before saving
file.Name = "prefix_" + file.Name
}
app.Save(record) // Files are saved automatically
Finding files
field := record.FindFileFieldByFile("document.pdf")
if field != nil {
log.Printf("File found in field: %s", field.Name)
}
Record expansion
ExpandedOne()
Get a single related record from expanded data:
author := record.ExpandedOne("author")
if author != nil {
log.Println("Author:", author.GetString("name"))
}
ExpandedAll()
Get multiple related records from expanded data:
comments := record.ExpandedAll("comments")
for _, comment := range comments {
log.Println("Comment:", comment.GetString("text"))
}
Expanding records programmatically
records, _ := app.FindRecordsByFilter("posts", "", "-created", 10, 0)
expands := []string{"author", "category"}
failures := app.ExpandRecords(records, expands, nil)
if len(failures) > 0 {
log.Println("Some expansions failed:", failures)
}
Record cloning
Clone()
Create a shallow copy with all data, expand, and flags:
clonedRecord := record.Clone()
Fresh()
Create a copy with only the latest collection fields data:
freshRecord := record.Fresh()
Original()
Get a copy with the original database state:
originalRecord := record.Original()
Record visibility
Hide fields
Hide fields from public serialization:
record.Hide("email", "password")
Unhide fields
Force unhide specific fields:
WithCustomData()
Allow exporting custom (non-schema) fields:
record.WithCustomData(true)
record.Set("computed_field", "value")
IgnoreEmailVisibility()
Ignore the email visibility check for auth records:
record.IgnoreEmailVisibility(true)
Advanced options
IgnoreUnchangedFields()
Only save fields that have changed:
record.IgnoreUnchangedFields(true)
record.Set("title", "New Title")
app.Save(record) // Only updates the title field
Save without validation
if err := app.SaveNoValidate(record); err != nil {
log.Fatal(err)
}
Saving without validation bypasses all field validation rules. Use with caution.
Auth records
Finding auth records
// Find by email
user, err := app.FindAuthRecordByEmail("users", "test@example.com")
// Find by token
user, err := app.FindAuthRecordByToken(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
core.TokenTypeAuth,
)
Auth record helpers
// Check if record is auth
if record.Collection().IsAuth() {
email := record.Email()
verified := record.Verified()
// Password operations
record.SetPassword("newpassword123")
if record.ValidatePassword("oldpassword") {
log.Println("Password is correct")
}
// Token operations
record.RefreshTokenKey()
tokenKey := record.TokenKey()
}
Creating auth tokens
user, _ := app.FindAuthRecordByEmail("users", "test@example.com")
// Create a standard auth token (default duration)
token, err := user.NewAuthToken()
// Create a static token with custom duration
token, err := user.NewStaticAuthToken(24 * time.Hour)
Query builder
RecordQuery()
Create a custom query for advanced filtering:
import "github.com/pocketbase/dbx"
var records []*core.Record
err := app.RecordQuery("posts").
AndWhere(dbx.HashExp{"published": true}).
AndWhere(dbx.NewExp("views > {:minViews}", dbx.Params{
"minViews": 100,
})).
OrderBy("created DESC").
Limit(10).
All(&records)
if err != nil {
log.Fatal(err)
}
JSON operations
UnmarshalJSONField()
Unmarshal a JSON field into a struct:
type Metadata struct {
Author string `json:"author"`
Tags []string `json:"tags"`
}
var meta Metadata
err := record.UnmarshalJSONField("metadata", &meta)
if err != nil {
log.Fatal(err)
}
PublicExport()
Export only safe fields for public use:
publicData := record.PublicExport()
// Returns map[string]any with only visible fields
Type signature
type Record struct {
BaseModel
// Methods
Collection() *Collection
Get(key string) any
Set(key string, value any)
GetString(key string) string
GetInt(key string) int
GetBool(key string) bool
GetFloat(key string) float64
GetDateTime(key string) types.DateTime
GetStringSlice(key string) []string
ExpandedOne(relField string) *Record
ExpandedAll(relField string) []*Record
Clone() *Record
Fresh() *Record
Original() *Record
}