'use strict';
|
|
const runTest = async () => {
|
const MongoClient = require('mongodb').MongoClient;
|
let client;
|
let db;
|
let s1, s2;
|
try {
|
console.log('Creating database');
|
client = await MongoClient.connect('mongodb://localhost:27017');
|
db = client.db('testdb');
|
await db.dropDatabase();
|
|
let collection = await db.createCollection('testcoll');
|
await db.createIndex('testcoll', \{id: 1}, \{unique: true});
|
await db.createIndex('testcoll', \{prop1: 1}, \{unique: true, partialFilterExpression: {prop1: {$exists: true}}});
|
|
console.log('Inserting documents');
|
s1 = client.startSession();
|
s1.startTransaction();
|
s2 = client.startSession();
|
s2.startTransaction();
|
|
await collection.insertOne(\{id:1}, \{session: s1});
|
await collection.insertOne(\{id:2}, \{session: s2});
|
|
await s1.commitTransaction();
|
await s2.commitTransaction();
|
await s1.endSession();
|
await s2.endSession();
|
|
console.log('Deleting documents');
|
s1 = client.startSession();
|
s1.startTransaction();
|
s2 = client.startSession();
|
s2.startTransaction();
|
|
await collection.deleteOne(\{id:1}, \{session: s1});
|
await collection.deleteOne(\{id:2}, \{session: s2});
|
|
await s1.commitTransaction();
|
await s2.commitTransaction();
|
await s1.endSession();
|
await s2.endSession();
|
|
} catch (error) {
|
if (s1 && s1.inTransaction()) {
|
await s1.abortTransaction();
|
s1.endSession();
|
}
|
if (s2 && s2.inTransaction()) {
|
await s2.abortTransaction();
|
s2.endSession();
|
}
|
throw error;
|
}
|
};
|
|
runTest()
|
.then (() => {
|
process.exit(0);
|
})
|
.catch(err => {
|
console.error(err);
|
process.exit(1);
|
});
|