Sequelize a promise based ORM for Nodejs

Posted By : Rohit Godara | 19-Dec-2018

Introduction to ORM

ORM or Object Relation Mapping could be a method of mapping between objects and relation info systems. an ORM acts like an interface between 2 system. ORM give benefits to developers from basic ones like saving time and energy and rather that specialize in business logic. The code is powerful rather than redundant. ORM helps in managing queries for multiple tables in an efficient manner. Lastly, an ORM (like sequelize) is capable to connect with totally different databases (which comes in handy once shift from one database to another).

Getting Started with Sequelize

Sequelize could be a promise-based ORM for Node.js. Sequelize is simple to be told and has dozens of cool options like synchronization, association, validation, etc. It conjointly has support for PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. I'm presumptuous you've got some kind of SQL database service started on your machine. I'm presently using MySQL.
Installation

Sequelize is offered via NPM and Yarn.

 

// Using NPM
$ npm install --save sequelize

# And one of the following:
$ npm install --save pg pg-hstore
$ npm install --save mysql2
$ npm install --save sqlite3
$ npm install --save tedious // MSSQL

// Using Yarn
$ yarn add sequelize

# And one of the following:
$ yarn add pg pg-hstore
$ yarn add mysql2
$ yarn add sqlite3
$ yarn add tedious // MSSQL

Setting up a connection

Sequelize can set up a connection pool on initialization, therefore, you ought to ideally solely ever produce one instance per information if you are connecting to the dB from one method. If you are connecting to the database from multiple processes, you'll need to make one instance per method, however, every instance ought to have the most connection pool size of maximum connection pool size divided by the number of instances. So, if you needed a goop association pool size of ninety and you had three employee processes, every process's instance ought to have a goop association pool size of thirty.

const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'|'sqlite'|'postgres'|'mssql',
  operatorsAliases: false,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },

  // SQLite only
  storage: 'path/to/database.sqlite'
});

//Or like below you can simply use a connection uri
const sequelize = new Sequelize('postgres://user:[email protected]:5432/dbname');


Test the connection by using the .authenticate() function like below to test the connection.

 
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

 

Your initial model

Model: A Model represents a table within the database. Instances of this category represent a database row.

Model instances operate with the conception of a dataValues property, that stores the particular values drawn by the instance. By default, the values from data values can even be accessed directly from the Instance, that is:

 

instance.field
// is the same as
instance.get('field')
// is the same as
instance.getDataValue('field')

 

However, if getters and/or setters are outlined for the field they're going to be invoked, rather than returning the worth from data values. 

Models are defined with sequelize.define('name', {attributes}, {options}).

 
const User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING
  },
  lastName: {
    type: Sequelize.STRING
  }
});

// force: false won't drop the table if already exists, true will drop the table if it already exists
User.sync({force: true}).then(() => {
  // Table created
  return User.create({
    firstName: 'Rohit',
    lastName: 'Godara'
  });
});

 

About Author

Author Image
Rohit Godara

Rohit is always ready to face challenges and likes to work with full dedication and coordination. He is always eager to learn new technologies so as to develop his skills and knowledge.

Request for Proposal

Name is required

Comment is required

Sending message..