Database
Database is a core component of database-type data sources (DataSource). Each database-type data source has a corresponding Database instance, accessible via dataSource.db. The main data source's database instance also has a convenient alias app.db. Familiarizing yourself with db's common methods is fundamental to writing server-side plugins.
Database Components
A typical Database consists of the following parts:
- Collection: Defines data table structure.
- Model: Corresponds to ORM models (usually managed by Sequelize).
- Repository: Repository layer that encapsulates data access logic, providing higher-level operation methods.
- FieldType: Field types.
- FilterOperator: Operators used for filtering.
- Event: Lifecycle events and database events.
Usage Timing in Plugins
Things Suitable for the beforeLoad Stage
At this stage, database operations cannot be performed yet. It is suitable for static class registration or event listening.
db.registerFieldTypes()- Register custom field typesdb.registerModels()- Register custom model classesdb.registerRepositories()- Register custom repository classesdb.registerOperators()- Register custom filter operatorsdb.on()- Listen to database-related events
Things Suitable for the load Stage
At this stage, all preceding class definitions and events have been loaded, so loading data tables won't have missing or omitted dependencies.
db.defineCollection()- Define new data tablesdb.extendCollection()- Extend existing data table configurations
However, for defining plugin built-in tables, it's more recommended to place them in the ./src/server/collections directory. See Collections.
Data Operations
Database provides two main ways to access and operate data:
Operations via Repository
The Repository layer is typically used to encapsulate business logic, such as pagination, filtering, permission checks, etc.
Operations via Model
The Model layer directly corresponds to ORM entities, suitable for lower-level database operations.
Which Stages Allow Database Operations?
Plugin Lifecycle
App Events
Database Events/Hooks
Related Links
- Collections - Define or extend data table structures with code
- DataSourceManager - Manage multiple data sources and their database instances
- Context - Access the
dbinstance in requests - Plugin - Plugin class lifecycle, member methods, and the
appobject - Event - Application-level and database-level event listening and handling

