So i have a problem with connecting to database in nest.js with typeorm and postgres. I have my local postgres instance running on docker. But when im running the app by yarn start it throws that error:
[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
My main app module
@Module({
imports: [TypeOrmModule.forRoot(configService.getTypeOrmConfig()), UsersModule, LoginModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
My config
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,
};
}
My env file
POSTGRES_HOST=127.0.0.1
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=kacluk123
POSTGRES_DATABASE=my_database
PORT=3000
MODE=DEV
Script to run 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
When I was facing this issue in my Nestjs and Typeorm project, my issue was my database wasn't actually created in my postgres, so I needed to create that. Note that my OS was Linux, I followed these steps for that.
sudo su - postgrespsql to enter into postgres cli commandsCREATE DATABASE databaseName;Note the semicolon in the end of postgres command, these are mandatory in syntax