Mid
From PDF
Node.js
Node.js
What are transactions and how are they handled? Transactions allow multiple database operations to execute atomically — either all succeed or none do — ensuring data consistency. ● In MongoDB (using Mongoose): const session = await mongoose.startSession(); session.startTransaction(); try {
wait User.create([{ name: 'Bob' }], { session });
wait Order.create([{ userId: user._id }], { session });
wait session.commitTransaction();
} catch (error) {
wait session.abortTransaction();
} finally {
session.endSession();
}
- In Sequelize (MySQL/PostgreSQL):
const t = await sequelize.transaction();
try {
wait User.create({ name: 'Bob' }, { transaction: t });
wait Order.create({ userId: user.id }, { transaction: t });
wait t.commit();
} catch (error) {
wait t.rollback();
}
Deployment & Production
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png