@nestjs/typeorm Documentation
repository·master·Indexed 24 days ago
https://github.com/nestjs/typeormOfficial NestJS integration for TypeORM, providing a dedicated module to use the TypeORM Object-Relational Mapper within the NestJS dependency injection system. Includes the TypeOrmModule for global and feature-based configuration, decorators like @InjectRepository(), @InjectDataSource(), and @InjectEntityManager(), and utility functions for generating injection tokens. Supports multiple data sources, async configuration via TypeOrmModuleAsyncOptions, and provides compatibility wrappers for TypeORM versions.
What's inside @nestjs/typeorm
Install @nestjs/typeorm and TypeORM
masterTo use TypeORM within a NestJS application, you must install both the
@nestjs/typeormwrapper and the coretypeormpackage using npm.$ npm i --save @nestjs/typeorm typeormDefine an entity using a class or an EntitySchema
masterWhen configuring TypeORM entities in NestJS, you can provide either a class decorated with@Entity()or a TypeORMEntitySchemaobject. TheEntityClassOrSchematype represents this union, allowing for both the decorator-based approach (standard for TypeScript classes) and the schema-based approach (useful for cases where you cannot or do not want to use decorators on the class itself).Compatibility for TypeORM Connection and AbstractRepository
masterThe
@nestjs/typeormpackage provides compatibility exports forConnectionandAbstractRepository. These symbols were removed in TypeORM v1.0.0 (replaced byDataSourcein TypeORM 0.3.0+).If you are using TypeORM v1.0.0 or newer, these exports will resolve to
undefined. If you are using TypeORM 0.3.x or older, they will resolve to the original TypeORM classes. This allows@nestjs/typeormto remain compatible across different major versions of TypeORM without causing runtime crashes or TypeScript errors whenskipLibCheckis disabled.Configure the PostgreSQL service via docker-compose.yml
masterThe project provides a
docker-compose.ymlfile to spin up a PostgreSQL database instance for testing or local development. The service is namedpostgresand uses thepostgres:18.4image.By default, the configuration sets the following environment variables and port mappings:
POSTGRES_USER:rootPOSTGRES_PASSWORD:rootPOSTGRES_DB:test- Host Port:
3306(mapped to container port5432)
Note: The host port is mapped to
3306, which is unconventional for PostgreSQL (typically5432) and may conflict if you have MySQL running on your host.version: "3" services: postgres: image: postgres:18.4 environment: POSTGRES_USER: root POSTGRES_PASSWORD: root POSTGRES_DB: test ports: - "3306:5432" restart: alwaysResolve CircularDependencyException
masterThe
CircularDependencyExceptionis thrown when the TypeORM module detects a circular dependency in your entity relationships or module imports.To resolve this, follow these steps:
- Use
forwardRef(): Ensure that both sides of a bidirectional relationship are decorated withforwardRef()to allow NestJS to resolve the dependency. - Avoid Barrel Files: Minimize the use of barrel files (
index.tsfiles that re-export multiple entities or modules), as they can cause unexpected circular dependency behavior during module resolution.
- Use
Resolve DuplicateDataSourceException
masterThe
DuplicateDataSourceExceptionis thrown when multiple TypeORM data sources are registered with the same name. In NestJS, if you register more than one data source usingTypeOrmModule.forRoot()orTypeOrmModule.forRootAsync(), each must have a uniquenameproperty to prevent them from overriding each other.If the error message mentions
default (unnamed), it means you have multiple registrations that did not specify anameproperty, causing them all to attempt to use the default name.Get the injection token for a Repository
masterUse
getRepositoryToken()to generate the unique injection token for an Entity or a Repository. This is useful when you need to manually resolve a repository from the NestJS dependency injection container, especially when working with multiple data sources.- If the
entityis a standard Entity class, it returns a string token likeEntityNameRepository. - If the
entityis anEntitySchema, it uses the schema's name. - If a custom
dataSourcename is provided, the token is prefixed with that name followed by an underscore (e.g.,connectionName_EntityNameRepository). - If the
entityis already a Repository class (custom repository), it usesgetCustomRepositoryToken()to generate the token.
- If the
Use TypeOrmModule to integrate TypeORM with NestJS
masterThe@nestjs/typeormpackage provides theTypeOrmModuleclass, which is the primary entry point for configuring and integrating TypeORM into a NestJS application. You typically useTypeOrmModule.forRoot()to establish a global connection to your database andTypeOrmModule.forFeature()to register specific entities within a module.Import TypeORM options interfaces
masterThelib/interfaces/index.tsfile serves as the entrypoint for all TypeORM-related interfaces in this package. You can import configuration and option interfaces from this entrypoint to ensure type safety when configuring your NestJS TypeORM integration.Configure the TypeORM module using TypeOrmModule.forRoot()
masterUseTypeOrmModule.forRoot()to register the TypeORM module with your database connection options. This method initializes the core TypeORM module. You can optionally provide anameas a second argument to overrideoptions.name, allowing you to configure the data source name separately from the connection options.Get the injection token for a DataSource
masterUse
getDataSourceToken()to retrieve the injection token for a TypeORMDataSource.- If you pass the string
'default', it returns theDataSourceclass itself. - If you pass a custom string name, it returns a string token formatted as
${name}DataSource. - If you pass a
DataSourceorDataSourceOptionsobject, it extracts the name and returns the corresponding token.
Note:
getConnectionTokenis a deprecated alias forgetDataSourceToken.- If you pass the string