最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - SequelizeModule — autoLoadModels[Nest] ERROR SequelizeModule Unable to connect to the database. Retrying - Stack Ov

programmeradmin3浏览0评论

I'm learning Nest.js, I'm trying to connect via SequelizeModule to my local postgres database, but I keep getting this error

Error when starting start:dev

[20:41:14] Starting compilation in watch mode...

[20:41:26] Found 0 errors. Watching for file changes.

[Nest] 14312  - 16.02.2025, 20:41:44     LOG [NestFactory] Starting Nest application...
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] AppModule dependencies initialized +1744ms
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] SequelizeModule dependencies initialized +0ms
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] UsersModule dependencies initialized +1ms
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] ConfigHostModule dependencies initialized +0ms
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] ConfigModule dependencies initialized +0ms
Executing (default): SELECT 1+1 AS result
Executing (default): SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'users'
Executing (default): CREATE TABLE IF NOT EXISTS "users" ("id" NUMBER SERIAL UNIQUE , "email" VARCHAR(255) NOT NULL UNIQUE, "password" VARCHAR(255) NOT NULL, "banned" BOOLEAN DEFAULT false, "banReason" VARCHAR(255), "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));
[Nest] 14312  - 16.02.2025, 20:41:46   ERROR [SequelizeModule] Unable to connect to the database. Retrying (1)...
Error
    at Query.run (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\dialects\postgres\query.js:76:25)
    at <anonymous> (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\sequelize.js:650:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at PostgresQueryInterface.createTable (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\dialects\abstract\query-interface.js:229:12)
    at Function.sync (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\model.js:1353:7)
    at Sequelize.sync (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\sequelize.js:825:9)
    at async D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\@nestjs\sequelize\dist\sequelize-core.module.js:123:17

At the beginning, it seems, some manipulations take place, but then an error is thrown without explaining what happened (at least I don't see anything useful here) and then 10 times error after error...

Connecting SequelizeModule in app.module
import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { UsersModule } from './users/users.module';
import { ConfigModule } from '@nestjs/config';
import { User } from './users/users.model';


@Module({
  controllers: [],
  providers: [],
  imports: [
    ConfigModule.forRoot({
      envFilePath: `.${process.env.NODE_ENV}.env`
    }),
    SequelizeModule.forRoot({
      dialect: 'postgres',
      host: process.env.POSTGRES_HOST,
      port: Number(process.env.POSTGRES_PORT),
      username: process.env.POSTGRES_USER,
      password: String(process.env.POSTGRES_PASSWORD),
      database: process.env.POSTGRES_DB,
      models: [User],
      autoLoadModels: false
    }),
    UsersModule,
  ],
})
export class AppModule {}

ps: password via String(), because for some reason it scolded me that it was not a string...

Using in users.module
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { SequelizeModule } from '@nestjs/sequelize';
import { User } from './users.model';

@Module({
  controllers: [UsersController],
  providers: [UsersService],
  imports: [
    SequelizeModule.forFeature([User]),
  ]
})
export class UsersModule {}

.env file

PORT=5000
POSTGRES_HOST=localhost
POSTGRES_USER=postgres
POSTGRES_PASSWORD=admin
POSTGRES_PORT=5432
POSTGRES_DB=ulbi-nest-course

I did some searching and found that it is related to the option autoLoadModels=true;

I tried to set it to false and the error really disappeared, but...

img no error

[20:43:19] Starting compilation in watch mode...

[20:43:23] Found 0 errors. Watching for file changes.

[Nest] 28912  - 16.02.2025, 20:43:25     LOG [NestFactory] Starting Nest application...
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] AppModule dependencies initialized +162ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] SequelizeModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] SequelizeCoreModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] UsersModule dependencies initialized +1ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] ConfigHostModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] SequelizeModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] ConfigModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [RoutesResolver] UsersController {/users}: +6ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [NestApplication] Nest application successfully started +3ms
Listening on port 5000
absolutely nothing happened in the database, no table was created:

postgresql tables

while I have users.model:

import { Column, DataType, Model, Table } from 'sequelize-typescript';
  
  
interface UserCreationAttrs {
  email: string,
  password: string,
}
  
@Table({tableName: 'users'})
export class User extends Model<User, UserCreationAttrs> {
  @Column({type: DataType.NUMBER, unique: true, autoIncrement: true, primaryKey: true})
  id: number;
  
  @Column({type: DataType.STRING, unique: true, allowNull: false})
  email: string;
  
  @Column({type: DataType.STRING, allowNull: false})
  password: string;
  
  @Column({type: DataType.BOOLEAN, defaultValue: false})
  banned: boolean;
  
  @Column({type: DataType.STRING, allowNull: true})
  banReason: string;
}

I'm learning Nest.js, I'm trying to connect via SequelizeModule to my local postgres database, but I keep getting this error

Error when starting start:dev

[20:41:14] Starting compilation in watch mode...

[20:41:26] Found 0 errors. Watching for file changes.

[Nest] 14312  - 16.02.2025, 20:41:44     LOG [NestFactory] Starting Nest application...
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] AppModule dependencies initialized +1744ms
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] SequelizeModule dependencies initialized +0ms
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] UsersModule dependencies initialized +1ms
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] ConfigHostModule dependencies initialized +0ms
[Nest] 14312  - 16.02.2025, 20:41:46     LOG [InstanceLoader] ConfigModule dependencies initialized +0ms
Executing (default): SELECT 1+1 AS result
Executing (default): SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'users'
Executing (default): CREATE TABLE IF NOT EXISTS "users" ("id" NUMBER SERIAL UNIQUE , "email" VARCHAR(255) NOT NULL UNIQUE, "password" VARCHAR(255) NOT NULL, "banned" BOOLEAN DEFAULT false, "banReason" VARCHAR(255), "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));
[Nest] 14312  - 16.02.2025, 20:41:46   ERROR [SequelizeModule] Unable to connect to the database. Retrying (1)...
Error
    at Query.run (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\dialects\postgres\query.js:76:25)
    at <anonymous> (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\sequelize.js:650:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at PostgresQueryInterface.createTable (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\dialects\abstract\query-interface.js:229:12)
    at Function.sync (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\model.js:1353:7)
    at Sequelize.sync (D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\sequelize\src\sequelize.js:825:9)
    at async D:\IT\IT\PROJECTS\my_projects\ulbi\backend_node_nest_docker\node_modules\@nestjs\sequelize\dist\sequelize-core.module.js:123:17

At the beginning, it seems, some manipulations take place, but then an error is thrown without explaining what happened (at least I don't see anything useful here) and then 10 times error after error...

Connecting SequelizeModule in app.module
import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { UsersModule } from './users/users.module';
import { ConfigModule } from '@nestjs/config';
import { User } from './users/users.model';


@Module({
  controllers: [],
  providers: [],
  imports: [
    ConfigModule.forRoot({
      envFilePath: `.${process.env.NODE_ENV}.env`
    }),
    SequelizeModule.forRoot({
      dialect: 'postgres',
      host: process.env.POSTGRES_HOST,
      port: Number(process.env.POSTGRES_PORT),
      username: process.env.POSTGRES_USER,
      password: String(process.env.POSTGRES_PASSWORD),
      database: process.env.POSTGRES_DB,
      models: [User],
      autoLoadModels: false
    }),
    UsersModule,
  ],
})
export class AppModule {}

ps: password via String(), because for some reason it scolded me that it was not a string...

Using in users.module
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { SequelizeModule } from '@nestjs/sequelize';
import { User } from './users.model';

@Module({
  controllers: [UsersController],
  providers: [UsersService],
  imports: [
    SequelizeModule.forFeature([User]),
  ]
})
export class UsersModule {}

.env file

PORT=5000
POSTGRES_HOST=localhost
POSTGRES_USER=postgres
POSTGRES_PASSWORD=admin
POSTGRES_PORT=5432
POSTGRES_DB=ulbi-nest-course

I did some searching and found that it is related to the option autoLoadModels=true;

I tried to set it to false and the error really disappeared, but...

img no error

[20:43:19] Starting compilation in watch mode...

[20:43:23] Found 0 errors. Watching for file changes.

[Nest] 28912  - 16.02.2025, 20:43:25     LOG [NestFactory] Starting Nest application...
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] AppModule dependencies initialized +162ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] SequelizeModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] SequelizeCoreModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] UsersModule dependencies initialized +1ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] ConfigHostModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] SequelizeModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [InstanceLoader] ConfigModule dependencies initialized +0ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [RoutesResolver] UsersController {/users}: +6ms
[Nest] 28912  - 16.02.2025, 20:43:25     LOG [NestApplication] Nest application successfully started +3ms
Listening on port 5000
absolutely nothing happened in the database, no table was created:

postgresql tables

while I have users.model:

import { Column, DataType, Model, Table } from 'sequelize-typescript';
  
  
interface UserCreationAttrs {
  email: string,
  password: string,
}
  
@Table({tableName: 'users'})
export class User extends Model<User, UserCreationAttrs> {
  @Column({type: DataType.NUMBER, unique: true, autoIncrement: true, primaryKey: true})
  id: number;
  
  @Column({type: DataType.STRING, unique: true, allowNull: false})
  email: string;
  
  @Column({type: DataType.STRING, allowNull: false})
  password: string;
  
  @Column({type: DataType.BOOLEAN, defaultValue: false})
  banned: boolean;
  
  @Column({type: DataType.STRING, allowNull: true})
  banReason: string;
}
Share Improve this question asked Feb 17 at 4:13 ralphralph 33 bronze badges New contributor ralph is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

2 Answers 2

Reset to default 0

Change your users.model.ts from:

@Column({ type: DataType.NUMBER, unique: true, autoIncrement: true, primaryKey: true })
id: number;

to:

@Column({ type: DataType.INTEGER, unique: true, autoIncrement: true, primaryKey: true })
id: number;

Have you tried logging the environment variables in process.env? They had likely not been loaded yet at the time of reading.

If you use ConfigModule, you need to be using ConfigService.get('xx') to retrieve the configuarion, as ConfigModule only loads the .env file while it's resolving (using the dotenv package).

If you directly access process.env in a sync configuration of a provider, then the values from the env file have not been loaded yet. (See also: https://docs.nestjs/techniques/configuration#environment-variables-loaded-hook)

Possible solutions:

  1. Load configuration values using ConfigService
SequelizeModule.forRootAsync({
  inject: [ConfigService]
  useFactory: (configService: ConfigService) => ({
    dialect: 'postgres',
    host: configService.get('POSTGRES_HOST'),
    port: Number(configService.get('POSTGRES_PORT')),
    username: configService.get('POSTGRES_USER'),
    password: configService.get('POSTGRES_PASSWORD'),
    database: configService.get('POSTGRES_DB'),
  }),
  models: [User],
  autoLoadModels: false
})
  1. Don't use ConfigModule/ConfigService and read process.env directly

In that case, you need to make sure that process.env is populated by calling dotenv/config early in the applicaiton bootstrap process (https://www.npmjs/package/dotenv)


See also:

  • Nest JS .env file variables are undefined even though im using ConfigModule
  • process.env's are undefined - NestJS
  • process.env.varible undefined in nest.js

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论