Vahid Najafi
Vahid Najafi

Reputation: 5243

Sequelize transaction prevent updating row

When I use the transaction in an update query, it prevents updating the row. Here is what I've done:

let t = await sequelize.transaction();
let updated = User.update({
    lastName: 'new lastname',
    firstName: 'new firstname'
}, 
{
where: { email:'[email protected]' },
// doesn't update with transaction
// transaction: t
})
.then(success(res))

Btw, it updates updatedAt column in the database, but other fields still the same. Any idea?

Update: This happens when I run some of queries in other functions and pass t (transaction) to the function.

Upvotes: 2

Views: 839

Answers (1)

Aryan
Aryan

Reputation: 3626

Try like this I think this will work here I am using async await not promise based method. Transaction I have used is Managed transactions Which is best to use if you want to use Transaction in your app

updateUser: async (req, res) => {
    sequelize.sequelize.transaction(async (t1) => {

        let data = await User.findOne({
            where: {
                id: req.body.id
            }
        });
        if (data) {
            await User.update(req.body, { where: { id: req.body.id } });
            return res.status(200).send(error.OK);
        }
        else {
            return res.status(422).send(error.DATA_NOT_FOUND);
        }
    }).catch(function (err) {
        console.log(err)
        return res.status(500).send(error.SERVER_ERROR);
    });
}

Upvotes: 2

Related Questions