Sequelize with expressjs and postgres

Dikshant Rajput
2 min readSep 20, 2022

--

In my previous blogs, I discussed setting up expressjs, middleware, and jwt token authentication. In this blog, I will be writing about connecting the express application with DB(Postgres) using the sequelize ORM library. Let’s get started.

Prerequisites:

  • Postgres DB (download it from here)
  • expressjs application
  • sequelize ORM package

I won’t be covering the setting up of express application as I have covered it in the past. I assume you have your express application configured. Let’s download the sequelize and node Postgres packages

npm install pg
npm install sequelize

Start the downloaded Postgres server and open up a command prompt and run

postgres --version

Note: If you want to access Postgres in the command line write this command:

psql or psql -U postgres

This will confirm that Postgres is installed on your system and remember the password set while installing the Postgres server. This will be used to connect with the DB.

Create a file and name it db.js or anything you want.

The Sequelize class expects 4 parameters

  • DB name
  • DB username
  • DB password
  • Object with DB host and dialect

NOTE: dialect is the DB name like Postgres, MySQL, sequelite, etc.

sequelize.authenticate() will check whether the connection is made successfully or not.

Let’s create a user model and apply crud operations on it and expose it using API.

Create a models directory and a User.js file in it

Create a routes directory and a user.js file in it.

The above function will get all the users from db using the findAll() method.

This will fetch a single user based on the id given.

This will create a new user.

This will update the user based on the id given.

This will delete the user based on the id given.

Check the database after performing all the operations. The complete file will look something like this:

The server.js file will look something like this:

Hit command npm start on the terminal and go to http://localhost:3000/users in postman and switch between the methods and test. That’s it.

I hope you like the blog and if you do, hit the clap icon and do follow me for more such blogs.

Drink water. Keep smiling…

--

--

Dikshant Rajput
Dikshant Rajput

No responses yet