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

未使用Docker的NestJS项目TypeOrmModule连接PostgreSQL失败

NestJS 连接 PostgreSQL 失败问题解决

问题描述

搭建非 Docker 环境的 NestJS 项目时,无法连接 PostgreSQL 数据库,核心错误提示:

ERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)... error: database "book_api" does not exist

相关配置代码如下:

typeorm.config.ts

import { TypeOrmModuleOptions } from '@nestjs/typeorm';

export const typeOrmConfig: TypeOrmModuleOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: '123456',
  database: 'book_api',
  entities: [__dirname + '/../**/*.entity.{ts,js}'],
  synchronize: true,
};

app.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { BooksModule } from './books/books.module';
import { typeOrmConfig } from './config/typeorm.config';

@Module({
  imports: [TypeOrmModule.forRoot(typeOrmConfig), BooksModule],
})
export class AppModule {}

Book 实体类(entity.ts)

import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Book extends BaseEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  title: string;

  @Column()
  author: string;

  @Column()
  category: string;

  @Column()
  year: number;
}

解决步骤

1. 确认 PostgreSQL 服务状态

  • Windows:打开服务管理器,找到postgresql-x64-xx(xx为版本号),确保服务处于正在运行状态。
  • macOS/Linux:终端执行 sudo systemctl status postgresql 查看状态,未运行则执行 sudo systemctl start postgresql 启动服务。

2. 手动创建目标数据库

TypeORM 的 synchronize: true 仅负责同步表结构,不会自动创建数据库,需手动创建book_api库:

命令行方式(psql)

  1. 终端执行 psql -U postgres,输入密码123456登录。
  2. 执行创建命令:
CREATE DATABASE book_api;
  1. 输入 \q 退出 psql。

图形化工具方式(pgAdmin)

  1. 打开 pgAdmin 并登录 PostgreSQL 服务器。
  2. 右键点击「Databases」→「Create」→「Database」。
  3. 在「Database」字段输入book_api,点击「Save」完成创建。

3. 核对配置参数

确认typeorm.config.ts中的以下参数与 PostgreSQL 实际配置一致:

  • username:默认超级用户为postgres,若自定义用户需修改
  • password:对应用户的登录密码
  • port:默认端口为5432,若修改过端口需同步调整

完成以上操作后,重启 NestJS 项目即可正常连接数据库。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:57:41