0

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

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

文件夹结构:

在此处输入图像描述

数据库.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!');
  }
}

应用模块.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 并没有被检测到。任何帮助是极大的赞赏。

4

1 回答 1

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!');
    }
}

于 2021-07-27T13:12:13.147 回答