Getting Started with Sequelize
— Backend, MySQl, Sequelize — 2 min read
The Node.js ORM Sequelize supports Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It is promise-based. Strong relational support, eager and slow loading, read replication, and other features are included.
An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using ~ StackOverflow
Let's discuss what that implies! What, is a promise-based ORM? Using object-oriented languages, you may query and manage data using an ORM, or object-relational mapping approach. Specifically, Javascript! An ORM is simply a library created in the language of your choosing that contains the necessary code instead of using SQL.
Although Sequelize works with a number of other database clients, this tutorial concentrates on Postgres.
Initializing the project
In an empty directory run the two commands and you will have a basic Node.js project initialized
yarn init -y
yarn add sequelize pg pg-hstore dotenv nodemon -D
Database Initialization
Now that the project is initialized. Before starting with any code, we must first initialize the database. If you are familiar with AWS, or any other cloud provider, I would suggest initializing a free/trial postgres instance to get started. AWS RDS Free tier is available if you open a new AWS account. I will not go in depth into how to set that up. You can read my guide here for the basics.
Database Connection
Let's begin by putting our models in our index.js file. With the use of a connection URL, Sequelize enables us to access the database.
const Sequelize = require('sequelize')const db = new Sequelize('postgres://localhost:5432/your-db', { logging: false,})
We can test our connection using:
try { await db.authenticate() console.log('Connection has been established successfully.')} catch (error) { console.error('Unable to connect to the database:', error)}
And that is how you can get started very easily with sequelize
and connect to a database. I will keep this article short. In the next part, I will try to elaborate how to use models to structure your data and define relationships.