TypeError: sequelize.transaction is not a function

Viewed 5213

I am getting the error: TypeError: sequelize.transaction is not a function. Using 4.x

const sequelize = require('sequelize');

await sequelize.transaction(async (transaction) => {
  await ProjectFile.destroy({
    where: projectId,
  }
      }, { transaction });
    });
3 Answers

The transaction object is inside your connector.

So, to call a transaction you need inform the connection first, like this:

const databaseConfig = {
    dialect: process.env.DB_TYPE,
    host: process.env.DB_HOST,
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME,

};

this.connection = new Sequelize(databaseConfig);

Where databseConfig is the configurations previously setted.

And then, on your interation:


const t = await database.connection.transaction();
await ProjectFile.destroy({
    where:  projectId,
    }
  }, { transaction: t });
// If everything ok
t.commit();
// otherwise
t.rollback();

And, in this way you can use the same transaction on a set of calls in your database before do the commit().

If you setup with sequelize-cli, try requiring your sequelize instance that is already connected to the database:

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