我正在使用 TypeORM 和 postgres 驱动程序设置 NestJs 应用程序。
我有所需的软件包(
"pg": "^8.11.0"
和其他 typeorm 软件包)。
数据源.ts
import 'reflect-metadata';
import { DataSource } from 'typeorm';
export const AppDataSource = new DataSource({
type: 'postgres',
url: process.env.DATABASE_URL,
host: process.env.DATABASE_HOST,
port: process.env.DATABASE_PORT
? parseInt(process.env.DATABASE_PORT, 10)
: 5432,
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
synchronize: process.env.DATABASE_SYNCHRONIZE === 'true',
dropSchema: false,
// keepConnectionAlive: true,
logging: process.env.NODE_ENV !== 'production',
entities: ['src/modules/**/entity/*.entity.ts'],
migrations: ['src/database/migrations/**/*.ts'],
ssl: false,
});
这个在 main.ts 中
import {
initializeTransactionalContext,
addTransactionalDataSource,
} from 'typeorm-transactional';
import { AppDataSource } from 'data-source';
async function bootstrap() {
initializeTransactionalContext();
addTransactionalDataSource(AppDataSource);
.
.
.
.
}
bootstrap();
app.module.ts
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [databaseConfig, appConfig],
envFilePath: ['.env'],
}),
TypeOrmModule.forRootAsync({
useClass: TypeOrmConfigService,
dataSourceFactory: async (options) => {
return new DataSource(options).initialize();
},
}),
UserModule,
],
})
export class AppModule {}
这是我尝试从 API 使用数据库时遇到的错误
TypeORMError: Driver not Connected
at PostgresDriver.obtainMasterConnection (/users/qwer/app-backend/src/driver/postgres/PostgresDriver.ts:1158:19)
at PostgresQueryRunner.connect (/users/qwer/app-backend/src/driver/postgres/PostgresQueryRunner.ts:110:18)
at PostgresQueryRunner.query (/users/qwer/app-backend/src/driver/postgres/PostgresQueryRunner.ts:244:47)
at PostgresQueryRunner.startTransaction (/users/qwer/app-backend/src/driver/postgres/PostgresQueryRunner.ts:176:24)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at EntityManager.transaction (/users/qwer/app-backend/src/entity-manager/EntityManager.ts:153:13)
请注意,我已将
synchronize
设置为 true
,因此当我启动应用程序时,它会在数据库中创建表。
我做错了什么或者这里缺少什么?
谢谢你
你忘记初始化前的await了吗?