【问题标题】:In typeorm with nestjs, ormconfig.json is not getting detected在带有 nestjs 的 typeorm 中,没有检测到 ormconfig.json
【发布时间】:2021-07-27 21:12:13
【问题描述】:

我对使用 typeorm 比较陌生。我正在尝试将 ormconfig.json 用于生产和开发环境,但我不断收到此错误:

Error during migration generation:
Error: Cannot find connection default because its not defined in any orm configuration files.

文件夹结构:

database.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection, getConnectionOptions } from 'typeorm';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useFactory: async () =>
        Object.assign(
          await getConnectionOptions(
            process.env.NODE_ENV === 'production' ? 'prod' : 'dev',
          ),
        ),
    }),
  ],
  exports: [TypeOrmModule],
})

export class DatabaseModule {
  constructor(connection: Connection) {
    if (connection.isConnected) console.log('DB Connected Successfully!');
  }
}

App.module.ts

...
@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    DatabaseModule,
    GraphQLModule.forRoot({
      playground: true,
      debug: true,
      autoSchemaFile: true,
    }),
    ComponentsModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

ormconfig.json

[
  {
    "name": "dev",
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "username": "...",
    "password": "...",
    "database": "yourcar",
    "entities": ["dist/**/entities/*{.ts,.js}"],
    "synchronize": true,
    "logging":true,
    "migrationsRun":true,
    "migrations":["dist/database/migrations/*{.ts,.js}"],
    "cli": {
      "migrationsDir":"src/database/migrations"
    }
  },
  {
    "name": "prod",
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "username": "...",
    "password": "...",
    "database": "yourcar",
    "entities": ["dist/**/entities/*{.ts,.js}"],
    "synchronize": false,
    "migrationsRun":true,
    "migrations":["dist/database/migrations/*{.ts,.js}"],
    "cli": {
      "migrationsDir":"src/database/migrations"
    }
  }
]

我认为 ormconfig.json 会在根目录中自动检测到,所以我尝试只使用一个环境并将 database.module.ts 更改为:

@Module({
  imports: [TypeOrmModule.forRoot(typeOrmConfig)],
})
export class DatabaseModule {
  constructor(connection: Connection) {
    if (connection.isConnected) {
      console.log('CONNECTED SUCCESS');
    }
  }
}

但这也不起作用,所以我猜 ormconfig 没有被检测到。非常感谢任何帮助。

【问题讨论】:

    标签: nestjs typeorm nestjs-config


    【解决方案1】:

    您可以使用 NestJS/config.env 文件来声明您的 BDD 配置。在您的database.module.ts 中,您可以设置此配置。

    例子:

    // app.module.ts
    @Module({
        imports: [
            ConfigModule.forRoot({
                isGlobal: true,
                cache: true,
                load: config,
                envFilePath: getEnvFiles(),
            }),
        ],
        controllers: [AppController],
        providers: [AppService],
    })
    export class AppModule {}
    
    // src/config/database.config.ts
    
    export default registerAs('database', () => ({
        host: process.env.DB_HOST || 'localhost',
        port: process.env.DB_PORT || 3306,
        user: process.env.DB_USER || 'root',
        password: process.env.DB_PASSWORD || 'root',
        database: process.env.DB_DATABASE || 'test',
        ...
    }));
    
    // database.module.ts
    
    @Module({
        imports: [
            TypeOrmModule.forRootAsync({
                inject: [ConfigService],
                useFactory: async (configService: ConfigService) => ({
                    type: 'postgres',
                    host: configService.get<string>('database.host'),
                    port: configService.get<number>('database.port'),
                    username: configService.get<string>('database.user'),
                    password: configService.get<string>('database.password'),
                    database: configService.get<string>('database.database'),
                    logger: new CustomORMLogger(new AdvancedConsoleLogger('all'), configService),
                    logging: configService.get<boolean>('database.logging'),
                    entities: configService.get<string[]>('database.entities'),
                    migrations: configService.get<string[]>('database.migrations'),
                    synchronize: true,
                }),
            }),
        ],
        exports: [TypeOrmModule],
    })
    export class DatabaseModule {
        constructor(connection: Connection) {
            if (connection.isConnected) console.log('DB Connected Successfully!');
        }
    }
    
    

    【讨论】:

    • 感谢您的快速回复。它并没有完全回答我的问题,但确实让我对在 nestjs w typeorm 中处理环境变量有所了解。我最初想知道如何设置和使用 ormconfig.json 中的 dev 和 prod 配置,就像在这个 vid 中一样:youtube.com/watch?v=4ELH8CT4J0A&t=26678s。不知何故,即使按照那里的步骤,程序似乎也没有检测到 ormconfig.json
    • 确实关于读取 ormconfig 文件这很奇怪......我不明白为什么
    猜你喜欢
    • 2020-04-30
    • 1970-01-01
    • 2019-09-21
    • 2019-06-27
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多