Nest.js中使用TypeORM的注意点

323 阅读1分钟

一、错误重现

在Nest.js中使用TypeORM使用时, 配置文件如下

// app.module.ts
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: ['**/entity/**'],
      synchronize: true,
    }),
  ],
})
export class AppModule {}

代码结构如下

image.png

那么极有可能得到如下的报错信息

SyntaxError: Cannot use import statement outside a module

那是因为entities是实体类所在目录,TypeORM将会查找这个目录下的所有实体类文件。而一个相对路径在nest中可能会因为不同的环境和不同部署位置时而无法找到实体类文件,最好修改为绝对路径。

二、解决办法

我们利用文件路径模块path来拼接绝对路径,以下命令将获取同级别目录下,所有文件名称中带entity.ts 或者entity.js的文件。

const entitiesPaths = [join(__dirname, '**', '*.entity.{ts,js}')]

所以最终的配置文件如下即可解决该报错问题。


// app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { join } from 'path';
const entitiesPaths = [join(__dirname, '**', '*.entity.{ts,js}')]
@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test',
      entities: entitiesPaths,
      synchronize: true,
    }),
  ],
})
export class AppModule {}

当然如果还是想用相对路径,那么可以修改为

entities: ['entity/**'],

欢迎关注我的公众号,每天学习一个小知识 【小明科技说】xuminjun2023