How to Connect Nodejs With Postgresql Along With Sequelize ORM?

By Prajwal Haniya

Techletter #18 | April 09, 2023

Connecting to the database is one of the important tasks before building any backend application. As my stack is JavaScript I will be using nodejs to build a backend application along with the PostgreSQL. As your product grows its very difficult to write complex queries manually. So, you need an ORM.

The ORM writes the complex queries automatically for you. Here, I will be using Sequelize ORM.

Now, lets connect node server to the PostgreSQL db along with the sequelize ORM.

Before proceeding make sure to install pg, sequelize, express pacakages.

Below is the folder structure

.
├── models/
│   └── User.js
├── db-connect.js
├── index.js
└── package.json

connect to the database

Make sure you have installed the postgres and pgadmin (just for GUI). The default port is 5432

const {Sequelize} = require('sequelize');

const sequelize = new Sequelize('test', 'user_name', 'password', {
    host: 'localhost',
    dialect: 'postgres',
    port: 5432,
    logging: false
});

module.exports = {sequelize};

Create your first model User -> models/User.js

Inside the models folder we will write all the database models that we want to create. You can create a new db and those will be synced whenever you start the node server.

const { DataTypes } = require('sequelize');

// import the sequelize. The above sequelize is from pacakge. The below one is from modules.
const {sequelize} = require('../db-connect');

/*
If your getting confused you can change the name of the module that you have exported.
*/

const User = sequelize.define('User', {
    firstName: {
        type: DataTypes.STRING,
        allowNull: true
    },
    lastName: {
        type: DataTypes.STRING,
        allowNull: false
    },
    email: {
        type: DataTypes.STRING,
        allowNull: true
    }
});

module.exports = {User};

Create a node server and sync the models

index.js

const express = require('express');
const {User} = require('./models/User');
const {sequelize} = require('./db-connect');

const app = express();

const PORT = 3000;

app.get('/', async (req, res) => {
    const user = await User.findAll();
    res.send(user);
});

app.listen(PORT, () => {
    console.log('Server is listening at port', PORT);
});

(async () => {
    await sequelize.sync();
    console.log('Database synchronized');
})();