How to use Sequelize

How to use Sequelize

Sequelize is a popular Node.js library for working with databases. It is an Object-Relational Mapping (ORM) tool that simplifies the process of working with databases in your Node.js applications. Sequelize provides a simple and powerful API for defining models, performing CRUD (create, read, update, delete) operations on those models, and organizing your database logic into reusable patterns.

Here is a brief overview of how to use Sequelize in a Node.js application:

Install Sequelize and its dependencies:

npm install sequelize

Define a model: A model is a class that represents a table in your database. You can define a model by creating a JavaScript class and decorating it with the Sequelize.Model method.

const { Model } = require('sequelize');

class User extends Model {}
User.init({
  name: Sequelize.STRING,
  email: Sequelize.STRING
}, {
  sequelize, // this is the connection instance
  modelName: 'user'
});

Connect to your database: You can connect to your database by creating a new instance of the Sequelize class and passing it a configuration object.

const Sequelize = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'
});

Perform database operations: Once you have defined your models and connected to your database, you can use the methods provided by Sequelize to perform operations on your data.

// Create a new user
const user = await User.create({
  name: 'John Smith',
  email: '[email protected]'
});

// Find all users
const users = await User.findAll();

// Update a user
await user.update({ name: 'John Doe' });

// Delete a user
await user.destroy();

Here are a few more things that you can do with Sequelize:

  • Define Relationships: You can define relationships between your models using associations. Sequelize provides several types of associations, including hasOne, belongsTo, hasMany, and belongsToMany, which allow you to specify how your models are related to each other.
const User = require('./user');
const Task = require('./task');

User.hasMany(Task);
Task.belongsTo(User);
  • Use Query Scopes: Query scopes allow you to define reusable query logic that can be applied to a model. This can be useful for creating custom methods on your models that encapsulate specific query logic.
const { Model } = require('sequelize');

class User extends Model {
  static scope(name, where) {
    return {
      where,
      model: this
    };
  }

  static async active() {
    const users = await User.scope('active', { active: true }).findAll();
    return users;
  }
}
User.init({
  name: Sequelize.STRING,
  email: Sequelize.STRING,
  active: Sequelize.BOOLEAN
}, {
  sequelize,
  modelName: 'user'
});

// Find all active users
const users = await User.active();
  • Use Transactions: You can use transactions to execute multiple database operations as a single unit of work. This can be useful for ensuring that your database remains in a consistent state in the event of an error or failure.
const { sequelize } = require('./models');

async function createUser() {
  try {
    const t = await sequelize.transaction();
    await User.create({ name: 'John Smith', email: '[email protected]' }, { transaction: t });
    await Task.create({ name: 'Task 1', userId: 1 }, { transaction: t });
    await t.commit();
  } catch (error) {
    console.error(error);
    await t.rollback();
  }
}

createUser();
  • Use Migrations: Migrations are a way to manage changes to your database schema over time. With Sequelize, you can use the sequelize-cli package to create and run migrations to update your database schema as you make changes to your application.
npm install -g sequelize-cli

sequelize init
sequelize model:generate --name User --attributes name:string,email:string
sequelize db:migrate

I hope this gives you a good idea of how to get started with Sequelize. There is much more that you can do with this library, so I recommend taking a look at the Sequelize documentation for more information.