Database is a database interaction tool provided by NocoBase, offering convenient database interaction capabilities for no-code and low-code applications. Currently supported databases are:
In the Database constructor, you can configure the database connection by passing in the options parameter.
For detailed configuration parameters, please refer to Constructor.
Database defines the database structure through Collection. A Collection object represents a table in the database.
After the database structure is defined, you can use the sync() method to synchronize the database structure.
For more detailed usage of Collection, please refer to Collection.
Database operates on data through Repository.
For more detailed data CRUD usage, please refer to Repository.
Signature
constructor(options: DatabaseOptions)Creates a database instance.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
options.host | string | 'localhost' | Database host |
options.port | number | - | Database service port, with a default port corresponding to the database used |
options.username | string | - | Database username |
options.password | string | - | Database password |
options.database | string | - | Database name |
options.dialect | string | 'mysql' | Database type |
options.storage? | string | ':memory:' | Storage mode for SQLite |
options.logging? | boolean | false | Whether to enable logging |
options.define? | Object | {} | Default table definition parameters |
options.tablePrefix? | string | '' | NocoBase extension, table name prefix |
options.migrator? | UmzugOptions | {} | NocoBase extension, parameters related to the migration manager, refer to the Umzug implementation |
addMigration()Adds a single migration file.
Signature
addMigration(options: MigrationItem)Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
options.name | string | - | Migration file name |
options.context? | string | - | Context of the migration file |
options.migration? | typeof Migration | - | Custom class for the migration file |
options.up | Function | - | up method of the migration file |
options.down | Function | - | down method of the migration file |
Example
addMigrations()Adds migration files from a specified directory.
Signature
addMigrations(options: AddMigrationsOptions): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
options.directory | string | '' | Directory where migration files are located |
options.extensions | string[] | ['js', 'ts'] | File extensions |
options.namespace? | string | '' | Namespace |
options.context? | Object | { db } | Context of the migration file |
Example
inDialect()Checks if the current database type is one of the specified types.
Signature
inDialect(dialect: string[]): booleanParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
dialect | string[] | - | Database type, possible values are mysql/postgres/mariadb |
getTablePrefix()Gets the table name prefix from the configuration.
Signature
getTablePrefix(): stringcollection()Defines a collection. This call is similar to Sequelize's define method, creating the table structure only in memory. To persist it to the database, you need to call the sync method.
Signature
collection(options: CollectionOptions): CollectionParameters
All options configuration parameters are consistent with the constructor of the Collection class, refer to Collection.
Events
'beforeDefineCollection': Triggered before defining a collection.'afterDefineCollection': Triggered after defining a collection.Example
getCollection()Gets a defined collection.
Signature
getCollection(name: string): CollectionParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | - | Collection name |
Example
hasCollection()Checks if a specified collection has been defined.
Signature
hasCollection(name: string): booleanParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | - | Collection name |
Example
removeCollection()Removes a defined collection. It is only removed from memory; to persist the change, you need to call the sync method.
Signature
removeCollection(name: string): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | - | Collection name |
Events
'beforeRemoveCollection': Triggered before removing a collection.'afterRemoveCollection': Triggered after removing a collection.Example
import()Imports all files in a directory as collection configurations into memory.
Signature
async import(options: { directory: string; extensions?: ImportFileExtension[] }): Promise<Map<string, Collection>>Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
options.directory | string | - | Path of the directory to import |
options.extensions | string[] | ['ts', 'js'] | Scan for specific suffixes |
Example
The collection defined in the ./collections/books.ts file is as follows:
Import the relevant configuration when the plugin loads:
registerFieldTypes()Registers custom field types.
Signature
registerFieldTypes(fieldTypes: MapOf<typeof Field>): voidParameters
fieldTypes is a key-value pair where the key is the field type name and the value is the field type class.
Example
registerModels()Registers custom data model classes.
Signature
registerModels(models: MapOf<ModelStatic<any>>): voidParameters
models is a key-value pair where the key is the model name and the value is the model class.
Example
registerRepositories()Registers custom repository classes.
Signature
registerRepositories(repositories: MapOf<RepositoryType>): voidParameters
repositories is a key-value pair where the key is the repository name and the value is the repository class.
Example
registerOperators()Registers custom data query operators.
Signature
registerOperators(operators: MapOf<OperatorFunc>)Parameters
operators is a key-value pair where the key is the operator name and the value is the function that generates the comparison statement.
Example
getModel()Gets a defined data model class. If no custom model class was previously registered, it will return the default Sequelize model class. The default name is the same as the collection name.
Signature
getModel(name: string): ModelParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | - | Registered model name |
Example
Note: The model class obtained from a collection is not strictly equal to the registered model class, but inherits from it. Since Sequelize's model class properties are modified during initialization, NocoBase automatically handles this inheritance relationship. Except for the class inequality, all other definitions can be used normally.
getRepository()Gets a custom repository class. If no custom repository class was previously registered, it will return the default NocoBase repository class. The default name is the same as the collection name.
Repository classes are mainly used for CRUD operations based on data models, refer to Repository.
Signature
getRepository(name: string): RepositorygetRepository(name: string, relationId?: string | number): RepositoryParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | string | - | Registered repository name |
relationId | string | number | - | Foreign key value for relational data |
When the name is an association name like 'tables.relations', it will return the associated repository class. If the second parameter is provided, the repository will be based on the foreign key value of the relational data when used (querying, updating, etc.).
Example
Suppose there are two collections, posts and authors, and the posts collection has a foreign key pointing to the authors collection:
on()Listens for database events.
Signature
on(event: string, listener: (...args: any[]) => void | Promise<void>): voidParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| event | string | - | Event name |
| listener | Function | - | Event listener |
The event names support Sequelize's Model events by default. For global events, listen using the format <sequelize_model_global_event>, and for single Model events, use the format <model_name>.<sequelize_model_event>.
For parameter descriptions and detailed examples of all built-in event types, refer to the Built-in Events section.
off()Removes an event listener function.
Signature
off(name: string, listener: Function)Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| name | string | - | Event name |
| listener | Function | - | Event listener |
Example
auth()Database connection authentication. Can be used to ensure that the application has established a connection with the data.
Signature
auth(options: QueryOptions & { retry?: number } = {}): Promise<boolean>Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
options? | Object | - | Authentication options |
options.retry? | number | 10 | Number of retries on authentication failure |
options.transaction? | Transaction | - | Transaction object |
options.logging? | boolean | Function | false | Whether to print logs |
Example
reconnect()Reconnects to the database.
Example
closed()Checks if the database connection is closed.
Signature
closed(): booleanclose()Closes the database connection. Equivalent to sequelize.close().
sync()Synchronizes the database collection structure. Equivalent to sequelize.sync(), for parameters refer to the Sequelize documentation.
clean()Cleans the database, deleting all collections.
Signature
clean(options: CleanOptions): Promise<void>Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
options.drop | boolean | false | Whether to drop all collections |
options.skip | string[] | - | Configuration of collection names to skip |
options.transaction | Transaction | - | Transaction object |
Example
Removes all collections except for the users collection.
defineCollection()Creates the configuration content for a collection.
Signature
defineCollection(name: string, config: CollectionOptions): CollectionOptionsParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
collectionOptions | CollectionOptions | - | Same as all parameters of db.collection() |
Example
For a collection configuration file to be imported by db.import():
extendCollection()Extends the configuration content of a collection already in memory, mainly for file content imported by the import() method. This method is a top-level method exported by the @nocobase/database package and is not called through a db instance. The extend alias can also be used.
Signature
extendCollection(collectionOptions: CollectionOptions, mergeOptions?: MergeOptions): ExtendedCollectionOptionsParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
collectionOptions | CollectionOptions | - | Same as all parameters of db.collection() |
mergeOptions? | MergeOptions | - | Parameters for the npm package deepmerge |
Example
Original books collection definition (books.ts):
Extended books collection definition (books.extend.ts):
If the two files above are imported when calling import(), after being extended again with extend(), the books collection will have both title and price fields.
This method is very useful for extending collection structures already defined by existing plugins.
The database triggers the following corresponding events at different stages of its lifecycle. Subscribing to them with the on() method allows for specific processing to meet certain business needs.
'beforeSync' / 'afterSync'Triggered before and after a new collection structure configuration (fields, indexes, etc.) is synchronized to the database. It is usually triggered when collection.sync() (internal call) is executed and is generally used for handling logic for special field extensions.
Signature
Type
Example
'beforeValidate' / 'afterValidate'Before creating or updating data, there is a validation process based on the rules defined in the collection. Corresponding events are triggered before and after validation. This is triggered when repository.create() or repository.update() is called.
Signature
Type
Example
'beforeCreate' / 'afterCreate'Corresponding events are triggered before and after creating a record. This is triggered when repository.create() is called.
Signature
Type
Example
'beforeUpdate' / 'afterUpdate'Corresponding events are triggered before and after updating a record. This is triggered when repository.update() is called.
Signature
Type
Example
'beforeSave' / 'afterSave'Corresponding events are triggered before and after creating or updating a record. This is triggered when repository.create() or repository.update() is called.
Signature
Type
Example
'beforeDestroy' / 'afterDestroy'Corresponding events are triggered before and after deleting a record. This is triggered when repository.destroy() is called.
Signature
Type
Example
'afterCreateWithAssociations'This event is triggered after creating a record with hierarchical association data. It is triggered when repository.create() is called.
Signature
Type
Example
'afterUpdateWithAssociations'This event is triggered after updating a record with hierarchical association data. It is triggered when repository.update() is called.
Signature
Type
Example
'afterSaveWithAssociations'This event is triggered after creating or updating a record with hierarchical association data. It is triggered when repository.create() or repository.update() is called.
Signature
Type
Example
'beforeDefineCollection'Triggered before a collection is defined, e.g., when db.collection() is called.
Note: This is a synchronous event.
Signature
Type
Example
'afterDefineCollection'Triggered after a collection is defined, e.g., when db.collection() is called.
Note: This is a synchronous event.
Signature
Type
Example
'beforeRemoveCollection' / 'afterRemoveCollection'Triggered before and after a collection is removed from memory, e.g., when db.removeCollection() is called.
Note: This is a synchronous event.
Signature
Type
Example