Skip to content

Instantly share code, notes, and snippets.

@alexbjorlig
Created January 7, 2020 20:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbjorlig/890ff51184cf98961f3251c0c2af378f to your computer and use it in GitHub Desktop.
Save alexbjorlig/890ff51184cf98961f3251c0c2af378f to your computer and use it in GitHub Desktop.
Example of bulk write transaction with Mongo 4.0 in Node.js
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();
@DarthSHO
Copy link

Nice, but how do you pass the json data as a variable?

@alexbjorlig
Copy link
Author

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