Sling Academy
Home/Node.js/Sequelize.js: Addition and Subtraction Assignment Operators

Sequelize.js: Addition and Subtraction Assignment Operators

Last updated: December 29, 2023

Overview

Sequelize.js is a popular ORM (Object-Relational Mapping) library for Node.js, which provides a high-level abstraction for dealing with databases. It supports all kinds of database operations, and in this tutorial, we’ll explore how to use the addition and subtraction assignment operators in Sequelize.js. These operators are handy when you need to update numeric fields in your database by incrementing or decrementing their values.

We’ll start with basic examples of incrementing and decrementing values in Sequelize, then we will dive deeper into more complex scenarios, such as bulk operations and transactions. By the end of this article, you’ll be equipped to use these operators confidently in your web applications.

Getting Started with Sequelize

Before jumping into the addition and subtraction assignment operators, let’s ensure you have Sequelize set up. Install Sequelize and your chosen database driver via npm:

npm install sequelize
npm install pg pg-hstore // For PostgreSQL
npm install mysql2 // For MySQL
npm install sqlite3 // For SQLite
npm install tedious // For MS SQL Server

Next, you’ll need to configure Sequelize to connect to your database:

const Sequelize = require('sequelize');

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

With Sequelize set up, let’s define a model that we will use in our examples:

const User = sequelize.define('user', {
  username: Sequelize.STRING,
  balance: Sequelize.INTEGER
});

// Sync all models with the database
sequelize.sync();

Basic Addition and Subtraction in Sequelize

Addition and subtraction assignment operations are done using the increment and decrement methods provided by Sequelize instances. Here’s a simple example:

User.findByPk(1).then(user => {
  return user.increment('balance', { by: 50 });
}).then(user => {
  console.log(user.balance); // Increased by 50
});

To decrement a value, you would use the decrement method:

User.findByPk(1).then(user => {
  return user.decrement('balance', { by: 30 });
}).then(user => {
  console.log(user.balance); // Decreased by 30
});

These methods also accept multiple fields, useful if you need to update several fields simultaneously:

User.findByPk(1).then(user => {
  return user.increment({
    balance: 50,
    bonusPoints: 20
  });
}).then(user => {
  console.log(user.get({ plain: true })); // Shows updated balance and bonusPoints
});

Advanced Usage

Sequelize also allows the increment and decrement operations to be part of a transaction, which is critical for maintaining data integrity. This ensures that if something goes wrong during the operation, you can roll back the entire transaction. Here’s an example of how to perform an increment operation within a transaction:

sequelize.transaction(t => {
  return User.findByPk(1, { transaction: t })
    .then(user => {
      return user.increment('balance', { by: 50, transaction: t });
    });
}).then(result => {
  console.log('Transaction committed.');
}).catch(error => {
  console.log('Transaction rolled back due to: ', error);
});

Handling more complex cases, such as conditional updates or updates based on the result of other operations, involves additional Sequelize features:

User.findByPk(1)
  .then(user => {
    if (user.balance > 0) {
      return user.decrement('balance', { by: user.balance * 0.1 }); // Decrease balance by 10%
    }
  })
  .then(user => {
    // Further operations
  }).catch(error => {
    // Handle error
  });

Conclusion

In this tutorial, we’ve covered the basics of using addition and subtraction assignment operators in Sequelize.js. We started with simple increment and decrement operations and moved on to more advanced use cases involving multiple fields and transactions. Keep in mind the importance of transactions for data integrity, especially when performing operations that alter multiple records or depend on multiple steps.

Additionally, remember that while incrementing and decrementing are simple operations, they can have significant effects on your data model’s logic. Always ensure that you are performing these operations under appropriate conditions to maintain the integrity and consistency of your data.

As you continue developing with Sequelize, you’ll find these operators to be invaluable tools in your arsenal for managing and updating numerical data efficiently. Happy coding!

Next Article: Sequelize.js Error: Foreign key constraint is incorrectly formed [fixed]

Previous Article: Sequelize: How to Migrate Data from One Database to Another (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