Sling Academy
Home/Node.js/How to Use Enums in Sequelize.js

How to Use Enums in Sequelize.js

Last updated: December 29, 2023

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.

Next Article: What is Model Synchronization in Sequelize?

Previous Article: How to Run Sub Queries in Sequelize.js (3 Ways)

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates