Created
January 7, 2020 20:19
-
-
Save alexbjorlig/890ff51184cf98961f3251c0c2af378f to your computer and use it in GitHub Desktop.
Example of bulk write transaction with Mongo 4.0 in Node.js
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
import { Backend } from '../../db/connection'; | |
import { MongoClient, Db } from 'mongodb'; | |
import { setupCliEnv } from './setup-cli-env'; | |
export async function mongoTransactionTest() { | |
setupCliEnv('development', false); | |
const options = { | |
useNewUrlParser: true, | |
useUnifiedTopology: true, | |
}; | |
const client = await MongoClient.connect(config.mongo.connectionString, options); | |
const db = client.db('db-name'); | |
await db.collection('Account').deleteMany({}); | |
await db.collection('Account').insertMany([ | |
{ name: 'A', balance: 5 }, | |
{ name: 'B', balance: 5 }, | |
]); | |
const session = client.startSession(); | |
session.startTransaction(); | |
try { | |
// await db | |
// .collection('Account') | |
// .findOneAndUpdate({ name: 'A' }, { $set: { balance: 6 } }, { session }); | |
// await db | |
// .collection('Account') | |
// .findOneAndUpdate({ name: 'B' }, { $set: { balance: 6 } }, { session }); | |
await db.collection('Account').bulkWrite( | |
[ | |
{ | |
updateOne: { | |
filter: { name: 'A' }, | |
update: { $set: { balance: 6 } }, | |
}, | |
}, | |
{ | |
updateOne: { | |
filter: { name: 'B' }, | |
update: { $set: { balance: 6 } }, | |
}, | |
}, | |
], | |
{ session } | |
); | |
await db | |
.collection('Account') | |
.findOneAndUpdate({ name: 'B' }, { balance: 7 }, { session }); | |
await session.commitTransaction(); | |
} catch (error) { | |
console.log(`🐛 was unexpected: ${error.message}`); | |
} finally { | |
session.endSession(); | |
} | |
console.log('done! 😍'); | |
await client.close(); | |
process.exit(0); | |
} | |
mongoTransactionTest(); |
This gist is actually outdated, see here for up-to-date example https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, but how do you pass the json data as a variable?