Collections are usually managed via the Admin UI, but there are some situations where you may want to create or edit a collection programmatically (usually as part of a DB migration). PocketBase exposes several helpers to simplify the Collection model operations.

    const collection = $app.dao().findCollectionByNameOrId("example")
    const baseCollections = $app.dao().findCollectionsByType("base") const authCollections = $app.dao().findCollectionsByType("auth") const viewCollections = $app.dao().findCollectionsByType("view")
    const collection = new Collection({ // the id is autogenerated, but you can set a specific one if you want to // id: "...", name: "example", type: "base", listRule: null, viewRule: "@request.auth.id != ''", createRule: "", updateRule: "@request.auth.id != ''", deleteRule: null, schema: [ { name: "title", type: "text", required: true, options: { max: 10, }, }, { name: "user", type: "relation", required: true, options: { maxSelect: 1, collectionId: "ae40239d2bc4477", cascadeDelete: true, }, }, ], indexes: [ "CREATE UNIQUE INDEX idx_user ON example (user)" ], options: {} }) $app.dao().saveCollection(collection)
    const collection = new Collection() const form = new CollectionUpsertForm($app, collection) form.name = "example" form.type = "base" form.listRule = null form.viewRule = "@request.auth.id != ''" form.createRule = "" form.updateRule = "@request.auth.id != ''" form.deleteRule = null form.schema.addField(new SchemaField({ name: "title", type: "text", required: true, options: { max: 10, }, })) form.schema.addField(new SchemaField({ name: "user", type: "relation", options: { maxSelect: 1, collectionId: "ae40239d2bc4477", cascadeDelete: true, }, })) ... // validate and submit (internally it calls $app.dao().saveCollection(collection) in a transaction) form.submit()
    const collection = $app.dao().findCollectionByNameOrId("example") // change the collection name collection.name = "example_update" // add new field collection.schema.addField(new SchemaField({ name: "description", type: "text", })) $app.dao().saveCollection(collection)
    const collection = $app.dao().findCollectionByNameOrId("example") const form = new CollectionUpsertForm(app, collection) // change the collection name form.name = "example_update" // add new field form.schema.addField(new SchemaField{ name: "description", type: "text", }) // validate and submit (internally it calls $app.dao().saveCollection(collection) in a transaction) form.submit()
    const collection = $app.dao().findCollectionByNameOrId("example") $app.dao().deleteCollection(collection)