Skip to content

集成TypeORM和MySQL(一)

安装插件、完成基础配置

创建 MySQL 数据库

在 linux 服务器上搭建mysql环境,并创建 db_nest_orm 数据库

安装 MySQL 和 TypeORM

shell
pnpm install --save @nestjs/typeorm typeorm mysql2

配置路由前缀

api/v1

ts
// src/main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('api/v1');
  await app.listen(3000);
}
bootstrap();

完成 mysql 数据库配置

ts
// src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user/user.entity';
import { Log } from './log/log.entity';
import { Roles } from './roles/roles.entity';
import { Profile } from './profile/profile.entity';
import { ProfileModule } from './profile/profile.module';
import { LogModule } from './log/log.module';
import { RolesModule } from './roles/roles.module';

@Module({
  imports: [
    UserModule,
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: '47.92.68.193',
      port: 3306,
      username: 'root',
      password: 'Wuweijie1.',
      database: 'db_nest_orm',
      entities: [User, Log, Roles, Profile], // 每个实体对应一个实体表
      synchronize: true, // 同步本地的schema到数据库(每次创建新的实体类保存后,在数据库中都会自动生成实体表)(开发环境可用,生产禁用 false)
      logging: ['error'],
    }),
    ProfileModule,
    LogModule,
    RolesModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}