Database reader
TheGenericDatabaseReader interface provides read-only access to the database in queries. Access it via ctx.db in query and mutation functions.
Get a document by ID
Fetch a single document from the database by its ID:The ID of the document to fetch from the database.
The name of the table to fetch the document from (optional first parameter).
null if it no longer exists.
Query documents
Begin a query for a given table. Queries don’t execute immediately - they’re lazily evaluated when you consume the results.The name of the table to query.
QueryInitializer object to start building a query.
System tables
Access system tables like_storage (file metadata) and _scheduled_functions (scheduled function state):
Normalize ID
Returns the string ID format for an ID in a given table, or null if the ID is from a different table or is not valid:The name of the table.
The ID string to normalize.
GenericId<TableName> or null.
Database writer
TheGenericDatabaseWriter interface extends GenericDatabaseReader with write operations. Available as ctx.db in mutations.
All reads and writes within a single mutation are executed atomically - you never have to worry about partial writes leaving your data in an inconsistent state.
Insert
Insert a new document into a table:The name of the table to insert into.
The document to insert. System fields (
_id, _creationTime) are added automatically and should not be included.GenericId of the newly created document.
Patch
Patch an existing document, shallow merging it with the given partial document:undefined are removed. Fields not specified in the patch are left unchanged.
The ID of the document to patch.
The partial document to merge into the existing document.
patch for partial updates. Use replace when you want to overwrite the entire document.
Throws: An error if the document does not exist.
Replace
Replace the entire value of an existing document, overwriting its old value completely:patch, which does a shallow merge, replace overwrites the entire document. Any fields not included in the new value will be removed (except system fields _id and _creationTime).
The ID of the document to replace.
The new document. System fields can be omitted.
Delete
Delete an existing document:The ID of the document to remove.
.delete() directly on query results. Collect documents first, then delete each one individually.
Table scoped API
Scope the database to a specific table for cleaner syntax:Best practices
- Use
.withIndex()instead of.filter()for efficient queries. Define indexes in your schema for fields you query frequently. - Avoid
.collect()on unbounded queries - it loads all matching documents into memory. Prefer.first(),.unique(),.take(n), or pagination. - All mutations are atomic - reads and writes within a single mutation see a consistent snapshot and commit together.
- System fields like
_idand_creationTimeare automatically managed - don’t include them when inserting documents.