How to Use PostgreSQL With Sequelize in Node.js
Sequelize is a Node.js object-relational mapper (ORM) that provides an easy-to-use API for relational databases such as Oracle, PostgreSQL, MySQL, MariaDB, SQLite, and more.
Sign up forfree
Forgot your password?
Create an account
*Required: 8 chars, 1 capital letter, 1 number
By continuing, you agree to thePrivacy PolicyandTerms of Use.You also agree to receive our newsletters, you’re able to opt-out any time.

PostgreSQL is compatible with multiple programming languages, including JavaScript, making it an ideal choice for web and data-driven applications. Here you will learn to set up a Postgres database in Node.js using Sequelize.
Step 1: Installing Dependencies
Before you can use PostgreSQL, you need to install it on your system. To download PostgreSQL, navigate to thePostgreSQL websiteand choose your operating system. If you run into issues during this process on macOS, check outinstalling PostgreSQL on macOS.
Alternatively, you’re able to use PostgreSQL on the cloud by leveraging platforms such asElephantSQLthat offer PostgreSQL as a service.

Next, installsequelizeby running the following command:
Then, install the PostgreSQL database driver by running the command below:

Step 2: Connecting to a PostgreSQL Database
In your project’s source directory, create aconfigfolder. In theconfigfolder, create adb.jsfile. This file will contain all the code connecting your Node.js application to a PostgreSQL database.
Next, in yourdb.jsfile, importSequelizefromsequelize.

Next, you need to create aSequelizeinstance. This instance takes connection parameters such as the database name, username, and password as arguments. Alternatively, it takes a single connection URI as an argument.
For example:

Additionally, this constructor takes a configuration object as an optional argument.
Next, test your sequelize connection by adding the code below yourdb.jsfile:
The code block above calls thesequelize.authenticate()method to test if the connection is OK and prints “Connection has been established successfully.” to console if it is. If there’s a connection error, it prints “Unable to connect to the database:” along with the error.
Finally, export the sequelize instance and thetestDbConnectionfunction.
Step 3: Creating a Sequelize Model
In your project’s source directory, create amodelsfolder. This folder will contain all your sequelize models. Next, create a model file. The name you give the file should provide information about the model’s representation.
In your model file, import the sequelize instance.
Next, importDataTypesfromsequelize.
DataTypeslets you set the required data type for each property on your model.
You can create a new sequelize model representing a table in your database by calling thedefinemethod on your sequelize instance.
Thedefinemethod takes two arguments: The model name and an attributes object. The model name represents the name of the model. The attributes object represents the columns of the database, with each property representing a column.
Here’s an example of a sequelize model:
The code block above defines aUsermodel with anemail,fullName,age, andemployedproperties.
Theemailproperty is a string type that cannot be empty (allowNull: false) and also acts as the primary key for theUsertable (primaryKey: true). ThefullNameand theageproperty are a string (DataTypes.STRING) and integer type (DataTypes.INTEGER), respectively. Theemployedproperty is a boolean type with a default value offalse, which means that if it is not specified, it’ll be automatically set to false in the database.
Next, call thesyncmethod on your model. This method takes a configuration object as an argument. Depending on the options in the configuration object, thesyncmethod can:
The code block above creates the database table for theUsermodel if it doesn’t exist and does nothing if it exists.
Finally, export your model:
Querying a PostgreSQL Database
Sequelize provides various methods that allow you to interact with your PostgreSQL database without writing rawSQL commands.
Saving Data to PostgreSQL
To save data to a PostgreSQL database, call thecreatemethod on your model and pass an object that implements the PostgreSQL model as an argument.
The code block above creates aUserinstance ofmikein your database and autogenerates a unique id.
Retrieving Data From PostgreSQL
Data can be retrieved in several ways from a PostgreSQL database using sequelize, but it depends on the nature of the data you want to receive.
The most common methods to retrieve data are thefindOneandfindAllmethods. ThefindAllreturns all data instances that satisfy a given query, whilefindOnereturns the first instance that satisfies the query.
The above code will return all theUserinstances in the database.
you’re able to filter through the returned data using thewherestatement. This statement allows you to add certain conditions to the query. Your query will only return instances that meet those conditions.
The above code will return all theUserinstances with theiremployedproperty set tofalsein the database.
Updating Data on PostgreSQL
You can update data on the PostgreSQL database by calling theupdatemethod and passing a filter as an argument.
The above code changes all theUserinstances with anemployedvalue offalsetotrue.
Alternatively, you can update data by manually modifying the properties you want to change and calling thesavemethod on the instance.
The above code queries the database for a user having the email “mike@example.com” using thefindOnemethod. If the user is found, it reassigns the email property to “mike@example.org” and calls thesavemethod to update the database.
Deleting Data on PostgreSQL
you could delete data on PostgreSQL by calling thedestroymethod and passing a filter as an argument.
The above code queries the database for a user having the email “mike@example.org” and deletes the user from the database.
Benefits of Using PostgreSQL With Sequlize
Writing raw SQL queries to interact with a PostgreSQL database can be a hassle. With Sequelize, you may easily define models, create associations between them, and query the database with a simple and intuitive API. Alternatively, you can use other ORMs, such as TypeORM, to interact with a PostgreSQL database without the hassle of writing raw SQL queries.
Why not up your database game with TypeORM’s full-featured NestJS package?
Turn these settings on, and your iPhone will be so much better than before.
Goodbye sending links via other apps.
The fix was buried in one tiny toggle.
Now, I actually finish the books I start.
You don’t need to fork out for expensive hardware to run an AI on your PC.