Node.js › Databases & ORMs (MongoDB/Mongoose, SQL/Sequelize)
How do you implement database transactions in Node.js using Sequelize to ensure multiple related writes succeed or fail together?
IntermediateAnswer
Sequelize's transaction() method wraps multiple operations so that either all of them commit together or, if any operation throws, all of them are automatically rolled back -- essential for maintaining data consistency in multi-step operations like transferring funds between two accounts, where partially applying only one side of the transfer would leave the data in an invalid, inconsistent state.
const transaction = await sequelize.transaction();
try {
await Account.decrement('balance', { by: 100, where: { id: fromId }, transaction });
await Account.increment('balance', { by: 100, where: { id: toId }, transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}Real-world example A banking application wraps a funds transfer between two accounts in a Sequelize transaction, guaranteeing that if the increment on the receiving account fails for any reason after the decrement on the sending account already succeeded, the entire operation rolls back automatically rather than leaving money 'lost' from one account without arriving in the other.