Skip to content

Instantly share code, notes, and snippets.

@wertlex
Created September 23, 2017 19:22
Show Gist options
  • Save wertlex/3b021d2d5469692ebb434cc7c15e56fd to your computer and use it in GitHub Desktop.
Save wertlex/3b021d2d5469692ebb434cc7c15e56fd to your computer and use it in GitHub Desktop.
const mongoose = require('mongoose');
async function withTempDb(dbName, action) {
const mongoUri = `mongodb://localhost:27017/${dbName}`;
const opts = {useMongoClient: true, promiseLibrary: global.Promise };
const conn = mongoose.createConnection(mongoUri, opts);
const onceOpen = new Promise( resolve => conn.once('open', resolve ));
await onceOpen;
let result;
try {
result = await action(conn);
} finally {
await conn.dropDatabase();
await conn.close();
}
return result;
}
withTempDb('dummy', () => console.log('Sync ok'));
withTempDb('correct', async db => {
const collection = db.collection('languages');
await collection.insert({name: 'JS'});
console.log('correct async okay');
});
withTempDb('tempDB-incorrect', async db => {
const collection = db.collection('languages');
collection.insert({name: 'JS'});
console.log('not waiting for insert result here...');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment