Collections and fields

A collection is a table of records with fields you define, plus its own API rules and a REST API. Every app starts with two: _superusers (who can open the dashboard) and users (your app's accounts). You add the rest.

Three kinds

Kind What it is For
Base a plain table posts, orders, settings: anything
Auth a table whose records can sign in, with email, password, verification and the sign-in methods you turn on users, customers, staff; see Authentication
View a read-only table defined by a SQL SELECT over other collections reports, joins, counts

Every record has an id (15 characters, made for you unless you set one). Base and auth collections usually also get created and updated (autodate fields, added by default in the dashboard).

Create one in the dashboard

Open the dashboard (/_/), choose New collection, name it, add fields, and save. With automigrate on (the default for pocketone serve), saving writes a migration file to pb_migrations, so the change goes with your code when you deploy it. See Migrations.

The dashboard: collections in the sidebar, and the posts collection's records

The gear next to a collection's name opens its settings: its fields, its API rules and, for an auth collection, its sign-in options.

Editing the posts collection: its fields, each with its type and options

Create one from code

The same collection as a migration, so it's created on every copy of your app:

// pb_migrations/1732300000_create_posts.ts
migrate((app) => {
  const posts = new Collection({
    type: "base",
    name: "posts",
    listRule: "",          // anyone can list
    viewRule: "",          // anyone can view
    createRule: "@request.auth.id != ''", // signed-in users can create
    updateRule: "author = @request.auth.id",
    deleteRule: "author = @request.auth.id",
    fields: [
      { type: "text", name: "title", required: true, max: 200 },
      { type: "text", name: "slug" },
      { type: "editor", name: "body" },
      { type: "relation", name: "author", collectionId: app.findCollectionByNameOrId("users").id, maxSelect: 1 },
      { type: "bool", name: "published" },
      { type: "autodate", name: "created", onCreate: true },
      { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
    ],
    indexes: ["CREATE UNIQUE INDEX idx_posts_slug ON posts (slug)"],
  })
  app.save(posts)
}, (app) => {
  app.delete(app.findCollectionByNameOrId("posts"))
})
// migrations/1732300000_create_posts.go
func init() {
	m.Register(func(app core.App) error {
		users, err := app.FindCollectionByNameOrId("users")
		if err != nil {
			return err
		}
		posts := core.NewBaseCollection("posts")
		posts.ListRule = types.Pointer("")
		posts.ViewRule = types.Pointer("")
		posts.CreateRule = types.Pointer("@request.auth.id != ''")
		posts.UpdateRule = types.Pointer("author = @request.auth.id")
		posts.DeleteRule = types.Pointer("author = @request.auth.id")
		posts.Fields.Add(
			&core.TextField{Name: "title", Required: true, Max: 200},
			&core.TextField{Name: "slug"},
			&core.EditorField{Name: "body"},
			&core.RelationField{Name: "author", CollectionId: users.Id, MaxSelect: 1},
			&core.BoolField{Name: "published"},
			&core.AutodateField{Name: "created", OnCreate: true},
			&core.AutodateField{Name: "updated", OnCreate: true, OnUpdate: true},
		)
		posts.AddIndex("idx_posts_slug", true, "slug", "")
		return app.Save(posts)
	}, func(app core.App) error {
		posts, err := app.FindCollectionByNameOrId("posts")
		if err != nil {
			return err
		}
		return app.Delete(posts)
	})
}

A rule left unset (null, in Go nil) means only superusers may do that action; an empty string means anyone may. API rules explains the rest.

Field types

Type Stores Options Reference
text Any string value. help, min, max, pattern, autogeneratePattern, required, primaryKey JS · Go
editor HTML formatted text. help, maxSize, convertURLs, required JS · Go
number Numeric (float64) value. help, min, max, onlyInt, required JS · Go
bool A single true/false value. help, required JS · Go
email A single email string address. help, exceptDomains, onlyDomains, required JS · Go
url A single URL string value. help, exceptDomains, onlyDomains, required JS · Go
date A single types.DateTime value. help, min, max, required JS · Go
autodate Datetime value could be auto set on record create/update. onCreate, onUpdate JS · Go
select Single or multiple string values from a predefined list. help, values, maxSelect, required JS · Go
file Record file(s). help, maxSize, maxSelect, mimeTypes, thumbs, protected, required JS · Go
relation Single or multiple collection record references. help, collectionId, cascadeDelete, minSelect, maxSelect, required JS · Go
json Any serialized JSON value. help, maxSize, required JS · Go
geoPoint Latitude and longitude GPS coordinates. help, required JS · Go
password Bcrypt hashed strings (usually used only internally for the "password" auth collection system field). help, pattern, min, max, cost, required JS · Go

Every field also has name, hidden (left out of API answers; superusers still see it) and presentable (shown in the dashboard when another record points to this one). A field's value comes back from the API in its natural JSON form: a number for number, an array of ids for a multi-relation, file names for file.

Change a collection

Load it, change it, save it. Renaming a field keeps its data; removing one drops its column:

// pb_migrations/1732400000_posts_add_summary.ts
migrate((app) => {
  const posts = app.findCollectionByNameOrId("posts")
  posts.fields.add(new TextField({ name: "summary", max: 300 }))
  posts.fields.getByName("body").required = true
  app.save(posts)
}, (app) => {
  const posts = app.findCollectionByNameOrId("posts")
  posts.fields.removeByName("summary")
  posts.fields.getByName("body").required = false
  app.save(posts)
})
m.Register(func(app core.App) error {
	posts, err := app.FindCollectionByNameOrId("posts")
	if err != nil {
		return err
	}
	posts.Fields.Add(&core.TextField{Name: "summary", Max: 300})
	posts.Fields.GetByName("body").(*core.EditorField).Required = true
	return app.Save(posts)
}, func(app core.App) error {
	posts, err := app.FindCollectionByNameOrId("posts")
	if err != nil {
		return err
	}
	posts.Fields.RemoveByName("summary")
	posts.Fields.GetByName("body").(*core.EditorField).Required = false
	return app.Save(posts)
})

Saving a collection checks it first (a relation must point at a real collection, an index must be valid SQL), and fails with the reason if not.

View collections

A view collection is a SELECT that the API serves like any other collection, read-only. Its fields come from the query's columns, and it needs an id column:

migrate((app) => {
  app.save(new Collection({
    type: "view",
    name: "posts_per_author",
    listRule: "",
    viewQuery: "SELECT author AS id, COUNT(*) AS posts FROM posts GROUP BY author",
  }))
}, (app) => {
  app.delete(app.findCollectionByNameOrId("posts_per_author"))
})
m.Register(func(app core.App) error {
	view := core.NewViewCollection("posts_per_author")
	view.ListRule = types.Pointer("")
	view.ViewQuery = "SELECT author AS id, COUNT(*) AS posts FROM posts GROUP BY author"
	return app.Save(view)
}, func(app core.App) error {
	view, err := app.FindCollectionByNameOrId("posts_per_author")
	if err != nil {
		return err
	}
	return app.Delete(view)
})

Next