未使用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)
- 终端执行
psql -U postgres,输入密码123456登录。 - 执行创建命令:
CREATE DATABASE book_api;
- 输入
\q退出 psql。
图形化工具方式(pgAdmin)
- 打开 pgAdmin 并登录 PostgreSQL 服务器。
- 右键点击「Databases」→「Create」→「Database」。
- 在「Database」字段输入
book_api,点击「Save」完成创建。
3. 核对配置参数
确认typeorm.config.ts中的以下参数与 PostgreSQL 实际配置一致:
username:默认超级用户为postgres,若自定义用户需修改password:对应用户的登录密码port:默认端口为5432,若修改过端口需同步调整
完成以上操作后,重启 NestJS 项目即可正常连接数据库。
内容的提问来源于stack exchange,提问作者Indira Yulianti
相关产品推荐
相关产品推荐

