how to pass sequelize transaction to save method

How to Pass Sequelize Transaction to Save Method?

Sequelize is an ORM (object-relational mapping) library for Node.js that works with databases like MySQL, PostgreSQL, and SQLite. One of the useful features of Sequelize is the ability to use transactions to group multiple database operations into a single unit of work. Transactions can help ensure data integrity and consistency.

Step 1: Create a Sequelize Transaction

The first step is to create a Sequelize transaction using the sequelize.transaction() method.


const { sequelize } = require('./models');

sequelize.transaction((t) => {
  // your database operations here
});

Step 2: Pass the Transaction to Save Method

To pass the transaction to the save() method, you need to provide it as an option object with a key of transaction.


const { sequelize, Model } = require('./models');

sequelize.transaction((t) => {
  Model.create({ /* data */ }, { transaction: t }).then(() => {
    // success logic
  }).catch((error) => {
    // error logic
  });
});

If you are updating an existing record, you can pass the transaction option to the update() method instead.


Model.update({ /* data */ }, { where: { /* condition */ }, transaction: t }).then(() => {
  // success logic
}).catch((error) => {
  // error logic
});

Step 3 (Optional): Rollback the Transaction

If any of the database operations within the transaction fail, you can use the rollback() method to undo all changes made within the transaction.


sequelize.transaction((t) => {
  return Model.create({ /* data */ }, { transaction: t }).then(() => {
    return OtherModel.create({ /* data */ }, { transaction: t });
  }).then(() => {
    // success logic
  }).catch((error) => {
    // error logic
    return t.rollback();
  });
});

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe