Loading...
Loading...
Compare original and translation side by side
scripts/references/assets/scripts/references/assets/go.modgithub.com/pocketbase/pocketbaseRead references/go-framework.mdRead references/go-migrations.mdRead references/go-hooks-routes.mdpb_collections.pygo.modgithub.com/pocketbase/pocketbasereferences/go-framework.mdreferences/go-migrations.mdreferences/go-hooks-routes.mdpb_collections.pyreferences/gotchas.mdoptionsfieldsschemareferences/gotchas.mdoptionsfieldsschemaoptions// WRONG (v0.22) — "options" wrapper does not exist in v0.23+
{"name": "status", "type": "select", "options": {"values": ["draft", "published"], "maxSelect": 1}}
{"name": "avatar", "type": "file", "options": {"maxSelect": 1, "maxSize": 5242880}}
{"name": "author", "type": "relation", "options": {"collectionId": "...", "maxSelect": 1}}
// CORRECT (v0.23+) — all properties are top-level (flat)
{"name": "status", "type": "select", "values": ["draft", "published"], "maxSelect": 1}
{"name": "avatar", "type": "file", "maxSelect": 1, "maxSize": 5242880}
{"name": "author", "type": "relation", "collectionId": "...", "maxSelect": 1}selectfilerelationtextpb_collections.py createcollections.jsonpb_collections.py import"options": {fieldsschema// WRONG: {"name": "posts", "type": "base", "schema": [...]}
// CORRECT: {"name": "posts", "type": "base", "fields": [...]}SchemaField// WRONG: collection.schema.addField(new SchemaField({type: "select", options: {values: ["a"]}}))
// CORRECT: collection.fields.add(new SelectField({name: "status", values: ["a"]}))optionsfieldsschemaSelectFieldTextFieldRelationFielde.next()$app.findRecordById()$app.dao(){paramName}:paramName@collection?===pb_collections.pypb_migrations/migratecmd.MustRegister()Automigrate: truemain.go_ "yourmodule/migrations"main.gopackage migrationsfunc init()m.Register()types.Pointer("rule")*stringreturn e.Next()options// 错误写法(v0.22)—— v0.23+中不存在"options"包装器
{"name": "status", "type": "select", "options": {"values": ["draft", "published"], "maxSelect": 1}}
{"name": "avatar", "type": "file", "options": {"maxSelect": 1, "maxSize": 5242880}}
{"name": "author", "type": "relation", "options": {"collectionId": "...", "maxSelect": 1}}
// 正确写法(v0.23+)—— 所有属性均为顶层(扁平结构)
{"name": "status", "type": "select", "values": ["draft", "published"], "maxSelect": 1}
{"name": "avatar", "type": "file", "maxSelect": 1, "maxSize": 5242880}
{"name": "author", "type": "relation", "collectionId": "...", "maxSelect": 1}selectfilerelationtextpb_collections.py createpb_collections.py importcollections.json"options": {fieldsschema// 错误写法:{"name": "posts", "type": "base", "schema": [...]}
// 正确写法:{"name": "posts", "type": "base", "fields": [...]}SchemaField// 错误写法: collection.schema.addField(new SchemaField({type: "select", options: {values: ["a"]}}))
// 正确写法: collection.fields.add(new SelectField({name: "status", values: ["a"]}))optionsfieldsschemaSelectFieldTextFieldRelationFielde.next()$app.findRecordById()$app.dao(){paramName}:paramName@collection?===pb_collections.pypb_migrations/main.gomigratecmd.MustRegister()Automigrate: truemain.go_ "yourmodule/migrations"package migrationsfunc init()m.Register()types.Pointer("rule")*stringreturn e.Next()VERSION=$(curl -s https://api.github.com/repos/pocketbase/pocketbase/releases/latest | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'].lstrip('v'))")
ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
OS=$(uname -s | tr A-Z a-z)
curl -sL "https://github.com/pocketbase/pocketbase/releases/download/v${VERSION}/pocketbase_${VERSION}_${OS}_${ARCH}.zip" -o pb.zip && unzip -o pb.zip pocketbase && rm pb.zip./pocketbase superuser create admin@example.com <password>.env.env.gitignorenohup ./pocketbase serve --http=127.0.0.1:8090 > pb.log 2>&1 &python scripts/pb_health.pyVERSION=$(curl -s https://api.github.com/repos/pocketbase/pocketbase/releases/latest | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'].lstrip('v'))")
ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
OS=$(uname -s | tr A-Z a-z)
curl -sL "https://github.com/pocketbase/pocketbase/releases/download/v${VERSION}/pocketbase_${VERSION}_${OS}_${ARCH}.zip" -o pb.zip && unzip -o pb.zip pocketbase && rm pb.zip./pocketbase superuser create admin@example.com <password>.env.env.gitignorenohup ./pocketbase serve --http=127.0.0.1:8090 > pb.log 2>&1 &python scripts/pb_health.pybaseauthviewRead references/field-types.mdRead references/relation-patterns.mdRead references/api-rules-guide.mdnullnull""pb_collections.py createpb_collections.py import --file collections.json.js.goAutomigrate: truepb_hooks/*.pb.jsRead references/go-hooks-routes.mdreferences/e2e-testing.mdpb_e2e_helpersgo testbaseauthviewreferences/field-types.mdreferences/relation-patterns.mdreferences/api-rules-guide.mdnullnull""pb_collections.py createpb_collections.py import --file collections.json.jsAutomigrate: true.gopb_hooks/*.pb.jsreferences/go-hooks-routes.mdreferences/e2e-testing.mdpb_e2e_helpersgo testpb_collections.py get <name>pb_auth.py --collection users --identity ... --password ...nullRead references/e2e-testing.mdtest_e2e.pypb_e2e_helperscreateRule@request.body.X = @request.auth.idcascadeDeletenullpb_collections.py get <name>pb_auth.py --collection users --identity ... --password ...nullreferences/e2e-testing.mdpb_e2e_helperstest_e2e.pycreateRule@request.body.X = @request.auth.idcascadeDeletenull| Topic | Reference |
|---|---|
| Gotchas & pitfalls | |
| API rules design | |
| Relation patterns | |
| JS SDK (frontend) | |
| JSVM hooks (server) | |
| File handling | |
| E2E testing patterns | |
| Go framework setup | |
| Go migrations | |
| Go hooks & routes | |
| Production deployment (Docker, binary, proxy) | |
| React SPA frontend | |
| 主题 | 参考文档 |
|---|---|
| 常见陷阱 | |
| API规则设计 | |
| 关联关系模式 | |
| JS SDK(前端) | |
| JSVM钩子(服务端) | |
| 文件处理 | |
| 端到端测试模式 | |
| Go框架配置 | |
| Go迁移 | |
| Go钩子与路由 | |
| 生产部署(Docker、二进制、代理) | |
| React SPA前端 | |
curl -s https://api.github.com/repos/pocketbase/pocketbase/releases/latest | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'])"https://github.com/pocketbase/pocketbase/releases/download/v{VERSION}/pocketbase_{VERSION}_{OS}_{ARCH}.zip| Platform | Asset name |
|---|---|
| Linux amd64 | |
| Linux arm64 | |
| macOS amd64 | |
| macOS arm64 (Apple Silicon) | |
| Windows amd64 | |
undefinedcurl -s https://api.github.com/repos/pocketbase/pocketbase/releases/latest | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'])"https://github.com/pocketbase/pocketbase/releases/download/v{VERSION}/pocketbase_{VERSION}_{OS}_{ARCH}.zip| 平台 | 资源名称 |
|---|---|
| Linux amd64 | |
| Linux arm64 | |
| macOS amd64 | |
| macOS arm64(Apple Silicon) | |
| Windows amd64 | |
undefined
**Create a superuser:**
```bash
./pocketbase superuser create admin@example.com yourpasswordundefined
**创建超级用户:**
```bash
./pocketbase superuser create admin@example.com yourpasswordundefined
> **Important:** Do NOT use Bash tool's `&` alone — the process dies when the shell session ends. Always use `nohup`.
> **Agent instruction:** If the user's PocketBase is not running or not installed, always recommend downloading the latest version using the GitHub API one-liner above to determine the current version number.
> **重要提示:** 请勿仅使用Bash工具的`&` — 进程会在shell会话结束时终止。请始终使用`nohup`。
> **Agent指令:** 如果用户的PocketBase未运行或未安装,始终建议使用上述GitHub API单行命令确定当前版本号,然后下载最新版本。| Variable | Required | Default | Description |
|---|---|---|---|
| No | | PocketBase base URL |
| Yes* | — | Superuser email address |
| Yes* | — | Superuser password |
.envPB_URL=http://127.0.0.1:8090
PB_SUPERUSER_EMAIL=admin@example.com
PB_SUPERUSER_PASSWORD=your-password.env.env.gitignore| 变量 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|
| 否 | | PocketBase基础URL |
| 是* | — | 超级用户邮箱地址 |
| 是* | — | 超级用户密码 |
.envPB_URL=http://127.0.0.1:8090
PB_SUPERUSER_EMAIL=admin@example.com
PB_SUPERUSER_PASSWORD=your-password.env.env.gitignorepb_config.pypb_config.py| Export | Type | Description |
|---|---|---|
| | PocketBase base URL (from env or default |
| | Superuser email (from env) |
| | Superuser password (from env) |
| function | Low-level HTTP request to PB API |
| function | Auto-authenticated superuser request (retries on 401) |
| function | Get cached superuser bearer token |
| function | Print structured JSON output |
| exception | Raised on HTTP errors (has |
Do not invent exports that don't exist (e.g.,). Check this table or readget_configdirectly.pb_config.py
| 导出项 | 类型 | 描述 |
|---|---|---|
| | PocketBase基础URL(来自环境变量或默认值 |
| | 超级用户邮箱(来自环境变量) |
| | 超级用户密码(来自环境变量) |
| 函数 | 向PB API发送底层HTTP请求 |
| 函数 | 自动认证的超级用户请求(401时重试) |
| 函数 | 获取缓存的超级用户Bearer令牌 |
| 函数 | 打印结构化JSON输出 |
| 异常 | HTTP错误时抛出(包含 |
请勿虚构不存在的导出项(如)。请查看此表格或直接阅读get_config。pb_config.py
python scripts/pb_health.pypython scripts/pb_health.pypython scripts/pb_auth.pyPB_SUPERUSER_EMAILPB_SUPERUSER_PASSWORDPOST /api/collections/_superusers/auth-with-passwordpython scripts/pb_auth.pyPOST /api/collections/_superusers/auth-with-passwordPB_SUPERUSER_EMAILPB_SUPERUSER_PASSWORDpython scripts/pb_auth.py --collection users --identity user@example.com --password secretpython scripts/pb_auth.py --collection users --identity user@example.com --password secretRead references/auth-api.mdreferences/auth-api.mdpython scripts/pb_collections.py list
python scripts/pb_collections.py list --filter "name~'user'" --sort "-created"python scripts/pb_collections.py list
python scripts/pb_collections.py list --filter "name~'user'" --sort "-created"python scripts/pb_collections.py get posts
python scripts/pb_collections.py get pbc_1234567890python scripts/pb_collections.py get posts
python scripts/pb_collections.py get pbc_1234567890undefinedundefined
Collection types:
- `base` — Standard data collection
- `auth` — Auth collection (automatically adds email, password, username, etc.)
- `view` — Read-only SQL view (requires `viewQuery`)
> **Warning:** PocketBase ships with a `users` auth collection already created. Do **not** `POST` to create a new `users` collection — it will fail with a name conflict. Instead, use `PATCH /api/collections/users` (or `pb_collections.py update users '{...}'`) to customize the existing collection (add fields, change rules, etc.).
集合类型:
- `base` — 标准数据集合
- `auth` — 认证集合(自动添加邮箱、密码、用户名等字段)
- `view` — 只读SQL视图(需要`viewQuery`)
> **警告:** PocketBase默认已创建`users`认证集合。请勿`POST`创建新的`users`集合 — 会因名称冲突失败。请使用`PATCH /api/collections/users`(或`pb_collections.py update users '{...}'`)自定义现有集合(添加字段、修改规则等)。collectionIdpython scripts/pb_collections.py import --file collections.jsoncollections.json{
"collections": [
{
"name": "categories",
"type": "base",
"fields": [
{"name": "name", "type": "text", "required": true}
]
},
{
"name": "posts",
"type": "base",
"fields": [
{"name": "title", "type": "text", "required": true},
{"name": "category", "type": "relation", "collectionId": "categories", "maxSelect": 1}
],
"listRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''"
}
],
"deleteMissing": false
}parentpython scripts/pb_collections.py create '{"name":"categories","type":"base","fields":[{"name":"name","type":"text","required":true}]}'
python scripts/pb_collections.py update categories '{"fields":[{"name":"name","type":"text","required":true},{"name":"parent","type":"relation","collectionId":"categories","maxSelect":1}]}'"CREATE INDEX idx_name ON posts (title)"collectionIdcollectionIdpython scripts/pb_collections.py import --file collections.jsoncollections.json{
"collections": [
{
"name": "categories",
"type": "base",
"fields": [
{"name": "name", "type": "text", "required": true}
]
},
{
"name": "posts",
"type": "base",
"fields": [
{"name": "title", "type": "text", "required": true},
{"name": "category", "type": "relation", "collectionId": "categories", "maxSelect": 1}
],
"listRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''"
}
],
"deleteMissing": false
}parentpython scripts/pb_collections.py create '{"name":"categories","type":"base","fields":[{"name":"name","type":"text","required":true}]}'
python scripts/pb_collections.py update categories '{"fields":[{"name":"name","type":"text","required":true},{"name":"parent","type":"relation","collectionId":"categories","maxSelect":1}]}'"CREATE INDEX idx_name ON posts (title)"collectionIdpython scripts/pb_collections.py update posts '{"listRule":"@request.auth.id != '\'''\''","fields":[{"name":"title","type":"text","required":true},{"name":"content","type":"editor"},{"name":"status","type":"select","values":["draft","published"]}]}'python scripts/pb_collections.py update posts '{"listRule":"@request.auth.id != '\'''\''","fields":[{"name":"title","type":"text","required":true},{"name":"content","type":"editor"},{"name":"status","type":"select","values":["draft","published"]}]}'python scripts/pb_collections.py delete postspython scripts/pb_collections.py delete postspython scripts/pb_collections.py import --file collections.jsoncollections.json{"collections": [...], "deleteMissing": false}Read references/collections-api.mdpython scripts/pb_collections.py import --file collections.jsoncollections.json{"collections": [...], "deleteMissing": false}references/collections-api.mdpython scripts/pb_records.py list posts
python scripts/pb_records.py list posts --filter 'status="published"' --sort "-created" --expand "author" --page 1 --perPage 50python scripts/pb_records.py list posts
python scripts/pb_records.py list posts --filter 'status="published"' --sort "-created" --expand "author" --page 1 --perPage 50python scripts/pb_records.py get posts abc123def456789
python scripts/pb_records.py get posts abc123def456789 --expand "author,comments"python scripts/pb_records.py get posts abc123def456789
python scripts/pb_records.py get posts abc123def456789 --expand "author,comments"python scripts/pb_records.py create posts '{"title":"Hello World","content":"<p>My first post</p>","status":"draft"}'
python scripts/pb_records.py create posts --file record.jsonpython scripts/pb_records.py create posts '{"title":"Hello World","content":"<p>My first post</p>","status":"draft"}'
python scripts/pb_records.py create posts --file record.jsonpython scripts/pb_records.py update posts abc123def456789 '{"status":"published"}'python scripts/pb_records.py update posts abc123def456789 '{"status":"published"}'python scripts/pb_records.py delete posts abc123def456789python scripts/pb_records.py delete posts abc123def456789| Operator | Description | Example |
|---|---|---|
| Equal | |
| Not equal | |
| Comparison | |
| Contains (LIKE) | |
| Does not contain | |
| Array/multi-value field | |
(expr1 && expr2) || expr3| 运算符 | 描述 | 示例 |
|---|---|---|
| 等于 | |
| 不等于 | |
| 比较 | |
| 包含(LIKE) | |
| 不包含 | |
| 数组/多值字段 | |
(expr1 && expr2) || expr3-created+title@random-created+title@random--expand "author"--expand "author.profile"--expand "author,category"Read references/records-api.md--expand "author"--expand "author.profile"--expand "author,category"references/records-api.mdundefinedundefined
**Notes:**
- Restore replaces all data (no merge)
- Server becomes temporarily unavailable during restore
- Always create a backup of current data before restoring
**Details:** `Read references/backups-api.md`
**注意事项:**
- 恢复会替换所有数据(无合并)
- 恢复期间服务器会暂时不可用
- 恢复前请务必创建当前数据的备份
**详细信息:** 查看`references/backups-api.md`pb_collections.py create/update| Mode | Auto-generated file format | Directory | Requirement |
|---|---|---|---|
| Standalone | | | Enabled by default |
| Go package | | | |
pb_collections.py./pocketbase servego run . servepb_collections.py createpb_collections.py import --file collections.jsonpb_migrations/pb_collections.py create/update| 模式 | 自动生成文件格式 | 目录 | 要求 |
|---|---|---|---|
| 独立模式 | | | 默认启用 |
| Go包模式 | | | |
pb_collections.py./pocketbase servego run . servepb_collections.py createpb_collections.py import --file collections.jsonpb_migrations/pb_create_migration.pypython scripts/pb_create_migration.py "backfill_user_slugs"
python scripts/pb_create_migration.py "seed_categories" --dir ./pb_migrations{timestamp}_{description}.js// === UP ===// === DOWN ===pb_create_migration.pypython scripts/pb_create_migration.py "backfill_user_slugs"
python scripts/pb_create_migration.py "seed_categories" --dir ./pb_migrations{timestamp}_{description}.js// === UP ===// === DOWN ===| Pattern | UP | DOWN |
|---|---|---|
| Create collection | | |
| Add field | | |
| Remove field | | |
| Change rules | | Revert to original rule |
| Execute SQL | | Reverse SQL |
| Seed data | | Delete records |
Read references/migrations.mdRead references/field-types.md| 模式 | 升级操作 | 降级操作 |
|---|---|---|
| 创建集合 | | |
| 添加字段 | | |
| 删除字段 | | |
| 修改规则 | | 恢复为原始规则 |
| 执行SQL | | 反向SQL操作 |
| 插入种子数据 | | 删除记录 |
references/migrations.mdreferences/field-types.md{
"success": true,
"status": 200,
"data": { ... }
}{
"success": true,
"status": 200,
"data": { ... }
}| HTTP Status | Meaning | Resolution |
|---|---|---|
| 400 | Bad Request | Check request body. Validation error details in |
| 401 | Unauthorized | Token expired. Scripts auto-retry |
| 403 | Forbidden | Operation denied by API rules. Check rules |
| 404 | Not Found | Collection or record does not exist |
{
"success": false,
"status": 400,
"data": {
"status": 400,
"message": "Failed to create record.",
"data": {
"title": {
"code": "validation_required",
"message": "Missing required value."
}
}
}
}| HTTP状态码 | 含义 | 解决方法 |
|---|---|---|
| 400 | 错误请求 | 检查请求体。 |
| 401 | 未授权 | 令牌过期。脚本会自动重试 |
| 403 | 禁止访问 | API规则拒绝操作。检查规则 |
| 404 | 未找到 | 集合或记录不存在 |
{
"success": false,
"status": 400,
"data": {
"status": 400,
"message": "Failed to create record.",
"data": {
"title": {
"code": "validation_required",
"message": "Missing required value."
}
}
}
}| Task | Script | Detail Reference |
|---|---|---|
| Connection check | | — |
| Superuser auth | | |
| User auth | | |
| List collections | | |
| Get collection | | |
| Create collection | | |
| Update collection | | |
| Delete collection | | |
| Import collections | | |
| List records | | |
| Get record | | |
| Create record | | |
| Update record | | |
| Delete record | | |
| List backups | | |
| Create backup | | |
| Restore backup | | |
| Delete backup | | |
| Generate migration | | |
| API rules design | — | |
| Common pitfalls | — | |
| Relation patterns | — | |
| JS SDK reference | — | |
| JSVM hooks | — | |
| File handling | — | |
| Run E2E tests | | |
| E2E test helpers | Import from | |
| Go: build & run | | |
| Go: dev run | | |
| Go: create superuser | | |
| Go: manual migration template (seed data / data transforms only) | | |
| 任务 | 脚本 | 详细参考 |
|---|---|---|
| 连接检查 | | — |
| 超级用户认证 | | |
| 用户认证 | | |
| 列出集合 | | |
| 获取集合 | | |
| 创建集合 | | |
| 更新集合 | | |
| 删除集合 | | |
| 导入集合 | | |
| 列出记录 | | |
| 获取记录 | | |
| 创建记录 | | |
| 更新记录 | | |
| 删除记录 | | |
| 列出备份 | | |
| 创建备份 | | |
| 恢复备份 | | |
| 删除备份 | | |
| 生成迁移文件 | | |
| API规则设计 | — | |
| 常见陷阱 | — | |
| 关联关系模式 | — | |
| JS SDK参考 | — | |
| JSVM钩子 | — | |
| 文件处理 | — | |
| 运行端到端测试 | | |
| 端到端测试辅助工具 | 从 | |
| Go: 构建并运行 | | |
| Go: 开发模式运行 | | |
| Go: 创建超级用户 | | |
| Go: 手动迁移模板(仅适用于种子数据/数据转换) | | |