Skip to content

Instantly share code, notes, and snippets.

@richardscarrott
Created June 25, 2021 10:12
Show Gist options
  • Save richardscarrott/0567012a679d5110233e6f3dc5fdd304 to your computer and use it in GitHub Desktop.
Save richardscarrott/0567012a679d5110233e6f3dc5fdd304 to your computer and use it in GitHub Desktop.
MongoDB withTransaction
// The docs for mongodb native driver sessions are pretty bare. The best example I can find is
// https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions
// but the code is generally not pretty; I think the following is likely the most suitable API:
// const doc = withTransaction(async session => {
// const doc = await users.updateOne({ _id: id }, { $set: { email } }, { returnOriginal: false, session });
// await orders.updateMany({ email }, { $set: { userId: id } }, { session });
// return doc;
// });
const withTransaction = async <T>(
fn: (session: ClientSession) => Promise<T>
) => {
const session = mongoClient.startSession();
try {
let result: T;
await session.withTransaction(async () => {
// https://jira.mongodb.org/browse/NODE-2014
result = await fn(session);
});
// @ts-ignore
return result;
} finally {
await session.endSession();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment