Skip to content

Instantly share code, notes, and snippets.

@vip3r011
Created August 20, 2023 13:30
Show Gist options
  • Save vip3r011/a73e127caf45c8ff102b3093a402ad8f to your computer and use it in GitHub Desktop.
Save vip3r011/a73e127caf45c8ff102b3093a402ad8f to your computer and use it in GitHub Desktop.
Mongoose Transaction wrapper
/*
this needs replicaSet to work
*/
const mongoose = require('mongoose');
async function runTransaction(transactionFunction, ...args) {
let session = null;
try {
session = await mongoose.startSession();
session.startTransaction();
const result = await transactionFunction(...args);
await session.commitTransaction();
session.endSession();
return result;
} catch (err) {
if (session) {
await session.abortTransaction();
session.endSession();
}
throw err;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment