Skip to content

Instantly share code, notes, and snippets.

@drenther
Last active March 13, 2019 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drenther/4dd9e2b3da69d49aecb53b17474fed2c to your computer and use it in GitHub Desktop.
Save drenther/4dd9e2b3da69d49aecb53b17474fed2c to your computer and use it in GitHub Desktop.
Handling mongoose transactions using runInTransaction helper function
const { runInTransaction } = require('mongoose-transact-utils');
const { User } = require('./models');
// any queries or write you want to do using transaction
(async () => {
// runInTransction catches any error in the callback to abort the transaction session
// and then rethrows the error for you to handle the reporting
await runInTransaction(async session => {
// run any queries here
await addFriend('John', 'Jane', session);
});
console.log('John and Jane are friend now!');
})();
async function addFriend(nameA, nameB, session) {
const userA = await User.find({ name: nameA }).session(session);
const userB = await User.find({ name: nameB }).session(session);
userA.friends.push(userB._id);
userB.friends.push(userA._id);
await userA.save();
await userB.save();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment