TypeORM 集成
$ npm install --save @nestjs/typeorm typeorm mysql2/pg
安装过程完成后,我们可以将TypeOrmModule导入到根目录中AppModule。
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
entities: [],
synchronize: true, // 表格同步。用于开发测试阶段,如果表实体结构发生变化,自动删除重建数据库表格。
}),
],
})
export class AppModule {}
如果数据库配置不能是常量,可以使用异步方法:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [configuration]
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService): Promise<any> => ({
type: 'postgres',
host: configService.get('DB.host'),
port: configService.get('DB.port'),
username: configService.get('DB.username'),
password: configService.get('DB.password'),
database: configService.get('DB.database'),
entities: [join(__dirname, './core') + '/**/**.entity{.ts,.js}'],
entityPrefix: 't_',
synchronize: true
})
}),
],
controllers: [AppController],
providers: [AppService]
})
export class AppModule {}
文档
https://docs.nestjs.com/techniques/database
https://typeorm.bootcss.com/