我对使用 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 并没有被检测到。任何帮助是极大的赞赏。