Last active
March 13, 2019 11:42
-
-
Save drenther/4dd9e2b3da69d49aecb53b17474fed2c to your computer and use it in GitHub Desktop.
Handling mongoose transactions using runInTransaction helper function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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