MyInternships.in

Databases & Data Access

Node.js Database Transactions

A transaction groups several operations so they all succeed or all roll back. It is essential whenever one logical action writes to more than one place and a partial write would corrupt the data.


What is Database Transactions in Node.js?

A transaction groups several operations so they all succeed or all roll back. It is essential whenever one logical action writes to more than one place and a partial write would corrupt the data.

Database Transactions example

A MongoDB transaction
JavaScript
const session = await mongoose.startSession();
try {
  await session.withTransaction(async () => {
    await Application.create([{ jobId, userId }], { session });
    await Job.updateOne({ _id: jobId }, { $inc: { applicantCount: 1 } }, { session });
    await User.updateOne({ _id: userId }, { $inc: { appliedCount: 1 } }, { session });
  });
} finally {
  await session.endSession();
}

How this works

Every operation must receive the session, or it runs outside the transaction and will not roll back. withTransaction also retries automatically on transient errors.

Key points to remember

  • MongoDB transactions require a replica set — they do not work on a standalone server.
  • Keep transactions short; they hold locks and block other writes.
  • In SQL, use BEGIN / COMMIT / ROLLBACK on a single pooled connection.

Common mistakes with Database Transactions

  • Omitting { session } on one operation, silently leaving it outside the transaction.
  • Making an HTTP call inside a transaction, holding locks for the network round trip.

Node.js Database Transactions— Interview Questions & FAQs

When do I need a database transaction?+

When one logical action touches several documents or tables and a partial write would leave the data inconsistent — transferring funds, creating an order with line items, or updating counters alongside a record.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships