Getting Started With Sequelize with Postgres: Part 1
Connecting with postgres database through sequelize
At first, open the terminal and get inside the project directory. Initialize an empty npm package.json file to install all the required dependencies using
npm init
Installing required dependencies
Install sequelize and postgres driver for this tutorial.
npm install sequelize
npm install pg ph-hstore
Importing sequelize package
Create a index.js file and type
const Sequelize = require('sequelize')
Instantiating the sequelize instance
Before this, make sure to open the postgres cli and log in to it and create a database.
For this test, I have already created a database named `sequelizetraining`
const sequelize = new Sequelize(
'sequelizetraining', // Database name that should be created before
'postgres', // Postgres username
'bishal@123', // Postgres password for the username
{
dialect: 'postgres' // For using postgres, will vary for other databases
}
)
Authenticating to make connection
Checking if the connection is successful. This is required only to check if the connection is successful. We can omit this code in our future projects.
sequelize.authenticate().then(() => {
console.log("Connection successful.")
}).catch(err => {
console.log(err)
})
Complete code
const Sequelize = require('sequelize')
const sequelize = new Sequelize(
'sequelizetraining', // Database name that should be created before
'postgres', // Postgres username
'bishal@123', // Postgres password for the username
{
dialect: 'postgres' // For using postgres, will vary for other databases
}
)
sequelize.authenticate().then(() => {
console.log("Connection successful.")
}).catch(err => {
console.log(err)
})
Conclusion
This is how we connect to the database through sequelize. More on this on part 2.