如何在 Nest.JS 中使用 .env 文件设置 Type ORM 的配置

oba*_*ram 5 javascript node.js typeorm nestjs

我想使用.env文件设置 TypeORM 的配置,但是当我尝试运行迁移脚本时遇到问题。

我做了什么:

1.在package.json中添加脚本

    "migration:generate": "node_modules/.bin/typeorm migration:generate -n",
    "migration:run": "node_modules/.bin/typeorm migration:run",
    "migration:revert": "node_modules/.bin/typeorm migration:revert",
Run Code Online (Sandbox Code Playgroud)

2.在app.module*中导入TypeOrmModule

    TypeOrmModule.forRootAsync({
        imports: [ConfigModule],
        inject: [ConfigService],
        useFactory: (configService: ConfigService) => ({
          type: 'mysql',
          host: configService.get('HOST'),
          port: +configService.get<number>('PORT'),
          username: configService.get('DATABASE_USERNAME'),
          password: configService.get('DATABASE_PASSWORD'),
          database: configService.get('DATABASE'),
          entities: [__dirname + '/**/*.entity{.ts,.js}'],
          synchronize: true,
        })
      }
    )],
Run Code Online (Sandbox Code Playgroud)

3.在根文件夹中创建.env文件

    HOST=localhost
    PORT=5432
    DATABASE_USER=dbuser
    DATABASE_PASSWORD=dbpassword
    DATABASE=dbname
Run Code Online (Sandbox Code Playgroud)

现在我尝试运行这样的迁移脚本:

npm run migration:generate -n AddUserTable
Run Code Online (Sandbox Code Playgroud)

我收到这样的错误:

Error during migration generation:
Error: No connection options were found in any orm configuration files.
Run Code Online (Sandbox Code Playgroud)

根据文档,它应该是一些ormconfig.json但它也应该与.env一起使用。请告诉我,我的情况有什么问题吗?

小智 2

关于错误消息,您应该在根项目中添加 ormconfig.json。在这种情况下,.env 文件不相关。