Database is an important 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 provides the convenient app.db alias. Familiarizing yourself with db's common methods is fundamental to writing server-side plugins.
A typical Database consists of the following parts:
At this stage, database operations are not allowed. Suitable for static class registration or event listening.
db.registerFieldTypes() — Custom field typesdb.registerModels() — Register custom model classesdb.registerRepositories() — Register custom repository classesdb.registerOperators() — Register custom filter operatorsdb.on() — Listen to database-related eventsAt 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 configurationsFor defining plugin built-in tables, it's more recommended to place them in the ./src/server/collections directory. See Collections.
Database provides two main ways to access and operate data:
The Repository layer is usually used to encapsulate business logic, such as pagination, filtering, permission checks, etc.
The Model layer directly corresponds to ORM entities, suitable for lower-level database operations.
| Stage | Database Operations Allowed |
|---|---|
staticImport | No |
afterAdd | No |
beforeLoad | No |
load | No |
install | Yes |
beforeEnable | Yes |
afterEnable | Yes |
beforeDisable | Yes |
afterDisable | Yes |
remove | Yes |
handleSyncMessage | Yes |
| Stage | Database Operations Allowed |
|---|---|
beforeLoad | No |
afterLoad | No |
beforeStart | Yes |
afterStart | Yes |
beforeInstall | No |
afterInstall | Yes |
beforeStop | Yes |
afterStop | No |
beforeDestroy | Yes |
afterDestroy | No |
beforeLoadPlugin | No |
afterLoadPlugin | No |
beforeEnablePlugin | Yes |
afterEnablePlugin | Yes |
beforeDisablePlugin | Yes |
afterDisablePlugin | Yes |
afterUpgrade | Yes |
| Stage | Database Operations Allowed |
|---|---|
beforeSync | No |
afterSync | Yes |
beforeValidate | Yes |
afterValidate | Yes |
beforeCreate | Yes |
afterCreate | Yes |
beforeUpdate | Yes |
afterUpdate | Yes |
beforeSave | Yes |
afterSave | Yes |
beforeDestroy | Yes |
afterDestroy | Yes |
afterCreateWithAssociations | Yes |
afterUpdateWithAssociations | Yes |
afterSaveWithAssociations | Yes |
beforeDefineCollection | No |
afterDefineCollection | No |
beforeRemoveCollection | No |
afterRemoveCollection | No |