Sequelize Connection
Installation
To connect to a PostgreSQL database using Sequelize, you'll need to follow a few steps. Sequelize is a promise-based Node.js ORM (Object-Relational Mapper) that supports multiple databases, including PostgreSQL.
First, you need to install Sequelize and the PostgreSQL driver (pg and pg-hstore),npm install sequelize pg pg-hstore
Set Up Sequelize
Next, you need to import Sequelize in your Node.js application and create a new Sequelize instance to connect to your PostgreSQL database.const { Sequelize } = require('sequelize'); // Create a new instance of Sequelize const sequelize = new Sequelize('database_name', 'username', 'password', { host: 'localhost', dialect: 'postgres', port: 5432, // The default port for PostgreSQL }); // Test the connection sequelize.authenticate() .then(() => { console.log('Connection has been established successfully.'); }) .catch(err => { console.error('Unable to connect to the database:', err); });
database_name
: The name of your PostgreSQL database.username
: The username you use to connect to PostgreSQL.password
: The password associated with the username.host
: The host where your PostgreSQL server is running (typicallylocalhost
for local development).dialect
: Specifies the database dialect. In this case, it’s'postgres'
.port
: The port on which PostgreSQL is running. The default is5432
.Steps to connect with Sequelize
i) Install Sequelize and PostgreSQL driver using npm.ii) Set up Sequelize with your database credentials.
iii) Test the connection using
sequelize.authenticate()
.iv) Optionally, use environment variables for better security.
v) Define models and sync them with your database to create tables.