Here you will learn to set up a Postgres database in Node.js using Sequelize.

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.

elephant in forest

Image Credit: bundit jonwises/Shutterstock

In theconfigfolder, create adb.jsfile.

This file will contain all the code connecting your Node.js utility to a PostgreSQL database.

Next, in yourdb.jsfile, importSequelizefromsequelize.

Next, it’s crucial that you 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.

to console if it is.

Finally, export the sequelize instance and thetestDbConnectionfunction.

Step 3: Creating a Sequelize Model

In your projects 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.

DataTypeslets you set the required data key in for each property on your model.

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.

ThefullNameand theageproperty are a string (DataTypes.STRING) and integer pop in (DataTypes.INTEGER), respectively.

Next, call thesyncmethod on your model.

This method takes a configuration object as an argument.

The code block above creates aUserinstance ofmikein your database and autogenerates a unique id.

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 free 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.

The above code changes all theUserinstances with anemployedvalue offalsetotrue.

The above code queries the database for a user having the email mike@example.com using thefindOnemethod.