Skip to content

Instantly share code, notes, and snippets.

@lineus lineus/atest.js Secret
Created Jul 7, 2018

Embed
What would you like to do?
simple session example with transaction on 2 collections
#!/usr/bin/env node --no-deprecation
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017,localhost:27018,localhost:27019/gh-6663?replicaSet=rs');
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const schemaA = new Schema({
name: String
});
const schemaB = new Schema({
name: String
});
const A = mongoose.model('A', schemaA);
const B = mongoose.model('B', schemaB);
const a = new A({ name: 'Andrew' });
const b = new B({ name: 'Billy' });
async function run() {
await conn.dropDatabase();
await a.save();
await b.save();
const session = await A.startSession();
await session.startTransaction();
const foundA = await A.findOne({}, {}, { session });
await B.findOneAndUpdate({}, { name: foundA.name }, { session });
await session.commitTransaction();
session.endSession();
let newB = await B.findOne({});
console.log(`hello from ${newB.name}`);
return conn.close();
}
run().catch(console.error);
issues: ./atest.js
hello from Andrew
issues:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.