What is sequelize.js?

Share

Sequelize is a promise-based, Node.js ORM (Object-relational mapping) for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication, and more.

A great thing about Sequelize is that it does not care about your underlying database. You can easily switch databases by adjusting the configuration file, and your code will mostly remain the same.

Interaction between database and Node.js
Interaction between database and Node.js
  1. Install the relevant packages using npm or yarn.
$ npm i sequelize # This will install v6
# And one of the following:
$ npm i pg pg-hstore # Postgres
$ npm i mysql2
$ npm i mariadb
$ npm i sqlite3
$ npm i tedious # Microsoft SQL Server
  1. Configure your database.

You need a Sequelize instance to pass a connection URI. The authenticate() function can be used to test if the connection has been established.

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
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}

Modeling your database using Sequelize is very convenient. A model in Sequelize is basically a representation of a table in your database. A Model instance contains details about the entity it represents. Every model has a name in Sequelize.

Here is a basic example of modeling the data:

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');
const User = sequelize.define('User', {
// Model attributes are defined here
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
// allowNull defaults to true
}
}, {
// Other model options go here
});
svg viewer
Copyright ©2024 Educative, Inc. All rights reserved