An overview of the

  1. TypeORMIt’s a use decorator, rightTypeScriptSupports a very good ORM framework. inNestJSMedium, yes@nestjs/typeormUse decorators in an elegant wayTypeORM

Use the sample

  1. First export the database connection configuration in config/database.ts:

    export const DatabaseConfig = {
        type: 'mysql',
        host: '127.0.0.1',
        port: 3306,
        username: 'root',
        password: '123456',
        database: 'example',
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: false,
        migrations: ['database/migration/**/*.ts'],
        cli: {
            migrationsDir: 'database/migration/default',}}Copy the code
  2. Then import the Settings in ormconfig.ts to be used when typeOrm commands such as TypeOrm migration:generate are used as configuration to connect to the database. Json, ormconfig.js or ormconfig.ts can be used to set the database connection. Here we choose ts file with more flexibility.

    import { DataBaseConfig } from 'config/database'
    
    module.exports = DataBaseConfig
    Copy the code

    Note: Please make sure that ormconfig.ts is also in the compilation scope of tsconfig.json:

    { "include": [ "ormconfig.ts", ... ] . }Copy the code
  3. Import Settings in app.module.ts, use typeOrmModule.forroot (), in the NestJS framework, to connect to the database. After that, the Connection and EntityManager can be injected into the program. Json as the default parameter for forRoot(), we need to import the configuration manually because we are using ts files.

     import { Module } from '@nestjs/common'
     import { TypeOrmModule } from '@nestjs/typeorm'
     import { DataBaseConfig } from 'config/database'
    
     @Module({
     imports: [TypeOrmModule.forRoot(DataBaseConfig)],
     })
     export class ApplicationModule {}
    Copy the code
  4. In a specific module, register Repository under the current module with the following code. (Please create your own./example.entity file first)

    import { Module } from '@nestjs/common';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { Example } from './example.entity';
    
    @Module({
    imports: [TypeOrmModule.forFeature([Example])],
    })
    export class ExampleModule {}
    Copy the code
  5. You can then use Repository in dependency injection mode for services and controllers.

    import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Example } from './example.entity'; @Injectable() export class ExampleService { constructor( @InjectRepository(Example) public readonly repo: Repository<Example>, ) {} findAll(): Promise<Example[]> { return this.exampleRepo.find(); }}Copy the code

recommendations

  1. It is recommended to write the database connection configuration to the. Env file rather than using itormconfig.jsonThe way. This has the advantage of keeping sensitive information under the.env. It is also easy to extend connections to multiple databases. How to read configuration files see another article[NestJS] Configuration information and environment variables