Are you new to SQL or databases in general? This prompted the emergence of Object Relational Mappers (ORMs) to make the management of databases easier. Just as the name implies, they automatically map out the objects from our code in a relational database. Sequelize is indeed a popular ORM created for Node.js, and in this post, we'll be looking at Sequelize.js holistically, what it does and how to work with sequelize.js. But quickly before then, let's examine what an ORM is.
What is an ORM?Object Relational Mapping(ORM) is a technique that maps software objects to database tables. This technique lets you query and manipulates data from a database using an object-oriented paradigm, providing us with a programmatic way to connect our code to the database and control the persisted data, that way, we can focus more on the business logic and less on error-prone SQL. ORM helps developers to interact with objects instead of having actually to write any database queries.
One prime merit of ORM is its ability to support multiple databases, which include Postgres, MySQL, SQLite, and others. Unlike raw queries where moving applications to a different database has complexities, as the questions will have to be re-written. An ORM automatically switches the database when a value is tweaked in the configuration file. As earlier stated, Sequelize is a popular ORM. Let's dive in to explore how it is and how it works.
Sequelize is well known as a promise-based ORM for Node.js and io.js. Sequelize supports the following dialects; PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL and features reliable transaction support, relations, read replication, and more. Although there are several other Node ORM's, this spectacular ORM has thousands of GitHub stars and is used by tons of applications and can be traced far back to 2011 this unwavering existence has endeared it to its users. Sequelize is also distinctively structured with Multiple features that go on to include; queries, scopes, migration s, relations, transactions, raw queries, read replication, with loads of others.
Installation of sequelize:
const { Sequelize } = require('sequelize');
// Option 1: Passing a connection URI
const sequelize = new Sequelize('sqlite::memory:')
// Example for sqlite
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname')
// Example for postgres
// Option 2: Passing parameters separately (sqlite)
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'path/to/database.sqlite'
});
// Option 2: Passing parameters separately (other dialects)
const sequelize = new Sequelize('database', 'username', 'password',
{
localhost: 'localhost',
dialect: one of 'mysql' | 'mariadb' | 'postgres' | 'mssql'});