【问题标题】:Unable to connect to the database - NEST.JS and TypeORM无法连接到数据库 - NEST.JS 和 TypeORM
【发布时间】:2020-11-25 09:22:05
【问题描述】:

所以我在使用 typeorm 和 postgres 连接到 nest.js 中的数据库时遇到问题。我的本地 postgres 实例在 docker 上运行。但是当我通过 yarn start 运行应用程序时,它会抛出该错误:

[Nest] 12736   - 2020-08-05 10:05:22   [TypeOrmModule] Unable to connect to the database. Retrying (1)... +86ms 
QueryFailedError: no schematic representation of the creation of the object was indicated

我的主应用模块

@Module({
  imports: [TypeOrmModule.forRoot(configService.getTypeOrmConfig()), UsersModule, LoginModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

我的配置

  public getTypeOrmConfig(): TypeOrmModuleOptions {
    return {
      type: 'postgres',
      host: this.getValue('POSTGRES_HOST'),
      port: parseInt(this.getValue('POSTGRES_PORT')),
      username: this.getValue('POSTGRES_USER'),
      password: this.getValue('POSTGRES_PASSWORD'),
      database: this.getValue('POSTGRES_DATABASE'),
      entities: [__dirname + "/../**/*.entity{.ts,.js}"],
      synchronize: true,
    };
  }

我的环境文件

POSTGRES_HOST=127.0.0.1
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=kacluk123
POSTGRES_DATABASE=my_database
PORT=3000
MODE=DEV

运行 docker/postgres 的脚本

#!/bin/bash
set -e

SERVER="my_database_server";
PW="kacluk123";
DB="my_database";

echo "echo stop & remove old docker [$SERVER] and starting new fresh instance of [$SERVER]"
(docker kill $SERVER || :) && \
  (docker rm $SERVER || :) && \
  docker run --name $SERVER -e POSTGRES_PASSWORD=$PW \
  -e PGPASSWORD=$PW \
  -p 5432:5432 \
  -d postgres

# wait for pg to start
echo "sleep wait for pg-server [$SERVER] to start";
SLEEP 3;

# create the db 
echo "CREATE DATABASE $DB ENCODING 'UTF-8';" | docker exec -i $SERVER psql -U postgres
echo "\l" | docker exec -i $SERVER psql -U postgres

【问题讨论】:

  • 您是否已将 postgres 容器端口映射到您的机器端口? docker run postgres -p 5432:5432
  • 是的,我已经用 docker 脚本更新了帖子。
  • 如何获取configService的实例以便调用configService.getTypeOrmConfig
  • @JayMcDoniel 我是在其他文件中发起的单身人士。

标签: node.js postgresql docker nestjs typeorm


【解决方案1】:

当我在我的 Nestjs 和 Typeorm 项目中遇到这个问题时,我的问题是我的数据库实际上并没有在我的 postgres 中创建,所以我需要创建它。请注意,我的操作系统是 Linux,为此我遵循了这些步骤。

  • sudo su - postgres
  • psql 进入 postgres cli 命令
  • CREATE DATABASE databaseName;

注意 postgres 命令末尾的分号,这些在语法中是强制性的

【讨论】:

    猜你喜欢
    • 2020-07-13
    • 2021-12-14
    • 2021-05-26
    • 1970-01-01
    • 2019-11-01
    • 2021-10-19
    • 1970-01-01
    • 2020-12-11
    • 2020-05-12
    相关资源
    最近更新 更多