Sling Academy
Home/Node.js/How to Set Unsigned Integer Field in Sequelize.js

How to Set Unsigned Integer Field in Sequelize.js

Last updated: January 03, 2024

Introduction

Working with Sequelize means engaging with a robust ORM for Node.js. This tutorial will guide you through the process of setting unsigned integer fields using Sequelize.js, ensuring data integrity and extending the range of data you can store. Let’s dive into the best practices and advanced configurations.

Setting up Sequelize

Before delving into unsigned integers, ensure Sequelize is installed and properly configured in your project. If you haven’t done so, initialize Sequelize as follows:

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

const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'mysql' // or 'postgres', 'sqlite', 'mssql'
});

Now, you can define a model with an unsigned integer field in Sequelize:

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

class User extends Model {}

User.init({
  id: {
    type: DataTypes.INTEGER.UNSIGNED,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  }
  // additional fields...
}, {
  sequelize,
  modelName: 'user'
});

Basics of Unsigned Integers

In SQL databases, an ‘unsigned’ integer is a type of data that can only represent non-negative numbers. Sequelize supports this functionality through specialized data types.

To define an unsigned integer field in Sequelize, you would do the following within your model definition:

id: {
  type: DataTypes.INTEGER.UNSIGNED,
  primaryKey: true,
  autoIncrement: true
}

Advanced Unsigned Integer Usage

Beyond basic setup, Sequelize offers additional tweaks for unsigned integers, especially when working with foreign keys and indexes.

class Order extends Model {}

Order.init({
  userId: {
    type: DataTypes.INTEGER.UNSIGNED,
    references: {
      model: 'users',
      key: 'id'
    }
  }
  // additional fields...
}, {
  sequelize,
  modelName: 'order'
});

Indexing and Custom SQL with Unsigned Integers

To boost performance, especially with large data sets, indexing your unsigned integer fields is key:

User.init({
  // ...
}, {
  sequelize,
  indexes: [{
    unique: true,
    fields: ['id']
  }]
});

For custom SQL definitions, you can leverage Sequelize’s query interface:

sequelize.getQueryInterface().addIndex('Users', ['id'], {
  fields: 'id unsigned'
});

Handling Eager Loading with Unsigned Integers

Sequelize enables eager loading to optimize related data fetching. Consider the following when dealing with unsigned integers:

User.hasMany(Order, { foreignKey: 'userId' });
Order.belongsTo(User, { foreignKey: 'userId' });

// Eager loading
User.findAll({
  include: [{ model: Order }]
});

Validations and Constraints

Add validations and constraints to ensure the correctness of your unsigned integer fields:

User.init({
  // ...
  credits: {
    type: DataTypes.INTEGER.UNSIGNED,
    validate: {
      isNumeric: true,
      min: 0
    }
  }
  // ...
}, {
  // ...
});

Conclusion

In this tutorial, we’ve explored how to configure unsigned integer fields in Sequelize.js, from basic setup to more advanced features like indexing, constraints, and eager loading. By understanding and implementing these concepts, you can take full advantage of unsigned data types to enhance your application’s data management and performance.

Next Article: A Deep Dive into Sequelize’s Timestamps

Previous Article: Transactions in Sequelize.js: A Complete Guide

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