Atomic Transactions are very useful when one has to perform a indivisible and irreducible series of database operations, and with mongoDB the multi document atomic transactions were introduced in the version 4.0. While MongoDb is wiidely used along with NodeJS, I thought it would be helpful to have an example of performing atomic transactions in mongodb with nodejs.
MongoDB atomic transactions with NodeJS
var mongoose = require('mongoose');
async () => {
const session = await mongoose.startSession();
await session.startTransaction();
try {
const opts = { session, new: true };
// perform operations
} catch (error) {
await session.abortTransaction();
await session.endSession();
throw error;
}
}
Important things to remember:
- Every transaction has a session associated with it
- At a given time, at most only one open transaction for a session.
- If a session ends and it has an open transaction, the transaction aborts.
Top comments (0)