developerasun / myCodeBox-web

Open source code box for web developers.
Apache License 2.0
5 stars 0 forks source link

[BUG] server/database: Postgres not creating table #281

Closed developerasun closed 1 year ago

developerasun commented 1 year ago

Describe the bug

  1. Nestjs/Typeorm not loading variables from .env file
  2. Postgres throwing password error when the .env file is used
  3. Postgres not creating a table based on entity schema

To Reproduce Steps to reproduce the behavior:

  1. Go to nestjs app configured with postgress/typeorm
  2. Run npm/pnpm start:dev
  3. See error

Expected behavior

DB connected and creating a table automatically

Screenshots

postgress-db-pw

no-table

Additional context Add any other context about the problem here.

Labeling Add a proper label for the issue

developerasun commented 1 year ago

solution: install @nestjs/config and configure it like below.

npm i @nestjs/config dotenv

and import the config module in app.module.ts,

@Module({
  imports: [
    ConfigModule.forRoot(),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

and then load dotenv module in config file.

import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { Quiz } from 'src/modules/quiz/quiz.entity';
import * as dotenv from 'dotenv';

dotenv.config();

export const typeormOptions: TypeOrmModuleOptions = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: process.env.POSTGRES_PW,
  database: 'quiz',
  entities: [Quiz],
  synchronize: true, // Setting synchronize: true shouldn't be used in production - otherwise you can lose production data.
  autoLoadEntities: true,
};

check if the table is creatd in pg admin. table-created