You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM数据库初始化报错:Driver not Connected 问题求助

问题排查与解决方案

错误信息

Connected to database
Error during database initialization TypeORMError: Driver not Connected
at PostgresDriver.obtainMasterConnection (/Users/projectserver/node_modules/typeorm/driver/postgres/PostgresDriver.js:868:19)
at PostgresQueryRunner.connect (/Users/project/server/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:68:18)
at PostgresQueryRunner.query (/Users/project/server/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:174:47)
at DataSource.query (/Users/project/server/node_modules/typeorm/data-source/DataSource.js:346:42)
at /Users/project/server/dist/Database/connection.js:37:26

核心错误原因

  • 未初始化数据库连接:TypeORM的DataSource实例创建后,必须调用initialize()方法才能真正建立数据库连接,直接调用query()会因连接未就绪报错。
  • 语法错误:database配置项的默认值缺少闭合引号,"usv, 应为 "usv"。
  • 错误的连接状态提示:在连接未建立时就打印"Connected to database",导致状态判断混淆。

修正后的代码

connection.ts

import "reflect-metadata";
import { DataSource } from "typeorm";
import { Members } from "./entities/Members";
import { Users } from "./entities/Users";

export async function connectToDatabase() {
  const connection = new DataSource({
    type: "postgres",
    host: process.env.DB_HOST || "localhost",
    port: Number(process.env.DB_PORT) || 5432,
    username: process.env.DB_USERNAME || "postgres",
    password: process.env.DB_PASSWORD || "postgres",
    database: process.env.DB_NAME || "usv", // 修复引号缺失问题
    entities: [Users, Members],
    synchronize: true,
    logging: true,
    schema: "usv",
  });

  // 先执行初始化,建立真实连接
  await connection.initialize();
  console.log("Connected to database");

  // 添加表注释
  await connection.query(`
    COMMENT ON TABLE usv.users IS 'users for the various project'
  `);
  return connection;
}

index.ts

import express, { Application } from "express";
import http from "http";
import "reflect-metadata";
import { connectToDatabase } from "./Database/connection";

const app: Application = express();
const server = http.createServer(app);

const port = process.env.SERVER_PORT;

// 初始化数据库
connectToDatabase()
  .then(() => {
    console.log("Database initialization completed!");
    server.listen(port, () => {
      console.log(`Listening on port ${port}`);
    });
  })
  .catch((err) => {
    console.error("Error during database initialization", err);
  });

app.use(express.json());

额外注意事项

  • 确保PostgreSQL服务已启动,配置的host、port、username、password、database信息与实际环境匹配。
  • synchronize: true仅适合开发环境,生产环境建议关闭该选项,改用TypeORM迁移脚本管理数据库结构变更。

内容的提问来源于stack exchange,提问作者Tini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:15:18