简体   繁体   中英

Record array of objects with a sequelize transaction

I need to record an array of objects in a sequelize transaction.

I got a sequelize transaction where I record a Project(for example). Then I need to record some Tasks, I did it with the bulkCreate, but then I realize that I scaped the transaction calling the bulkCreate direct from the model Task.

try {
  const transaction = await db.transaction(t => {
    return Project.create(
      { ...req.body.projectFull.entity },
      { transaction: t }
    ).then(
      projectCreated => {
        let tarefas = req.body.projectFull.tasks;
        const addProjectId = function(object) {
          object.projectId = projectCreated.dataValues.id;
          return object;
        };
        let criarTarefas = tarefas.map(addProjectId);
        Task.bulkCreate(criarTarefas);
      },
      { transaction: t }
    );
  });

I expect to have the bulkCreate working inside my transaction not directly from the model. The code I provides works fine and record the data, but It scapes the transaction on bulkCreate

Hey i have to do this similar thing, and i didn't get to it yet, but i had read up on it back then and the example is as follows

return sequelize.transaction(t => {

  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(user => {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(result => {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(err => {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});

It looks to me like the comment above might be your problem... "make sure you return them"... you may have missed the return in the second part of your chain

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM