Skip to main content

Database

The database of choice is PostgreSQL as SQL database and MongoDB as NoSQL database. ORM is the industry standard, so you should stick to them. Every ORM allows you to write raw queries if needed. TypeORM is SQL ORM used for PostgreSQL and mongoose is ORM used for manipulating and fetching data in MongoDB.

PostgreSQL

Below we will install and configure PostgreSQL server. Depending on your operating system download and install package.

MacOs Install

brew update
brew install postgresql@15
brew services stop postgresql@15
brew services start postgresql@15
psql postgres

Ubuntu Install

sudo apt install postgresql postgresql-contrib
sudo service postgresql stop
sudo service postgresql start
sudo -u postgres psql

Database and user creation

create database <db_name>;
create user <db_user> with encrypted password '<db_user_pass>';
grant all privileges on database <db_name> to <db_user>;
\c <db_name>
\l
\dt
\du

TypeORM

TypeORM is an Object Relational Mapping (ORM) library that enables developers to seamlessly connect applications written in TypeScript/JavaScript with various relational databases. To configure TypeORM in a Node.js application, you must install the typeorm package and the corresponding database driver, followed by creating a TypeORM datasource configuration and defining the entities.

npm install --save typeorm reflect-metadata pg

The reflect-metadata package facilitates runtime reflection on types, and must be globally imported to function properly in our application. Driver package specific to the PostgreSQL database is pg.

Make sure you have enabled the following settings in tsconfig.json:

tsconfig.json
{
...
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
...
}

Next, create data-source.ts which holds your database connection settings and establishes initial database connection

data-source.ts
import "reflect-metadata";
import { DataSource } from "typeorm";
import { User } from "./user/entities/user.entity.ts";

export const AppDataSource = new DataSource({
type: "postgres",
host: "localhost",
port: 5432,
username: "<db_user>",
password: "<db_user_pass>",
database: "<db_name>",
synchronize: true,
logging: false,
entities: [],
migrations: [],
subscribers: [],
});
./user/entities/user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;

@Column()
firstName: string;

@Column()
lastName: string;

@Column()
email: string;
}
main.ts
import createServer from "common/utils/server";
import DataSource from "./data-source";

function startServer() {
const app = createServer();
app.listen("8000", () => {
console.log("Server is running on port 8000");
});
}

DataSource.initialize()
.then(() => startServer())
.catch(() => console.log("Database connection failed..."));