How to Connect PostgreSQL  with Nodejs

How to Connect PostgreSQL with Nodejs

Connect your database server with nodejs in just a seconds.

In this tutorial, we will learn how to "Connect Postgresql database with Nodejs".

Prerequisite

Before we get started, make sure all these technologies are installed on your local machine.

  1. Nodejs v+ 18 already installed,

  2. PostgreSQL Driver already installed;

Sample Project

In our sample project, we will build a simple database store that has the names of employees and salary range;

Create a new database collection

  1. Create a new database

     CREATE DATABASE organisation;
    
  2. Check if the database is created

     \l
    
  3. Connect to the database

     \c organisation;
    
  4. Create a data collection of employee

     CREATE TABLE employee (
         emp_id     INT PRIMARY KEY,
         first_name VARCHAR(50) NOT NULL,
         last_name VARCHAR(50) NOT NULL,
         gender CHAR(1),
         birthdate DATE,
         email VARCHAR(100) UNIQUE,
         salary INT
     );
    
  5. To check whether the employee table is created.

     \d employee;
    

Insert Table

Insert table is used for adding rows of data into the database. Now let's insert the data into your database, if you check your table using \d employee you would notice that the row and column of the table are empty.

INSERT INTO employee(emp_id, first_name, last_name, gender, birthdate, email, salary)
VALUES(1,'Annie','Smith','M', DATE '1988-01-09', 'emma@email.com',5000);

SELECT

SELECT will list all the data available in the employee table.

SELECT * FROM employee;

Create Our Nodejs App

Let's connect our Nodejs app to our PostgreSQL database. For more find the GitHub repository here: https://github.com/EmmaUmeh/NodePostgresql

  1. Initialize your Nodejs project

     npm init --y
    
  2. Install PostgreSQL database dependency

     npm install pg
    
  3. Create a databasepostgres.js file

     const {Client} = require('pg');
    
     const client = new Client({
        host: "localhost",
         user: "postgres", //default PostgreSQL username
         port: 5432, //default PostgreSQL port number
         password: "*****", //default PostgreSQL password
         database: "postgres" 
     })
    
     client.connect(); //connect() connects our database
    
     client.query('SELECT * FROM employee', (err, res) => {
    
         return(!err) ? console.log(res.rows) : console.log(err.message);
    
     })
    
  4. Now let's run this to check whether it is connected.

     node databasepostgres
    
  5. In the terminal console, you would see the database running.

Conclusion

Furthermore, we have connected a simple database store using nodejs, what other technologies would you like to use in the future for your project, Let's us know in our comment section.