How to Use Enums in Sequelize.js

Updated: December 29, 2023 By: Guest Contributor Post a comment

Introduction

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It provides robust support for modeling and working with your database using an object-oriented approach. Enums or enumerated types are a feature of SQL databases which Sequelize also supports. Enums help in defining a column with a set of predefined values. This tutorial will explore how to define and use Enums in Sequelize, demonstrating practical code examples from basic to advanced usage.

Basic Usage of Enums in Sequelize

The most straightforward way to use an enum in Sequelize is to define it in a model:

const User = sequelize.define('user', {
  status: {
    type: Sequelize.ENUM,
    values: ['active', 'inactive', 'archived']
  }
});

This code defines a User model with a status column that can only have one of three values.

Advanced Usage of Enums in Sequelize

For more advanced scenarios, enums can be used with model validations, custom setters, and techniques to control the enum values dynamically:

// Using a virtual datatype to add custom validation and manipulation
const User = sequelize.define('user', {
  status: {
    type: Sequelize.VIRTUAL,
    get() {
      const rawValue = this.getDataValue('status');
      // Custom manipulation logic can be added here
      return rawValue;
    },
    set(value) {
      // Custom validation logic can be added here
      this.setDataValue('status', value);
    },
    validate: {
      isIn: {
        args: [['active', 'inactive', 'archived']],
        msg: 'Invalid status'
      }
    }
  }
});

This example demonstrates a more complex usage involving Sequelize’s virtual datatype.

Working with Enums in Migrations

It’s also vital to efficiently handle enums in migrations, creating or altering them during the database evolution:

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.changeColumn('Users', 'status', {
      type: Sequelize.ENUM('active', 'inactive', 'archived')
    });
  },
  down: (queryInterface, Sequelize) => {
    // Remove enum type. Necessary queries can be executed here.
  }
};

This migration example updates the ‘status’ column to use an enum type.

Conclusion

This tutorial covered the basics and advanced techniques for using enums in Sequelize, including how to define enums directly in your models, perform validations, and handle enums in migrations. By integrating enums into your Sequelize models, you can ensure valid data and minimize the need for extra validation logic in your application.