Skip to content

Instantly share code, notes, and snippets.

@joeywhelan
Last active January 20, 2019 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeywhelan/6e7acac5cebb79c7bef93234ffa13190 to your computer and use it in GitHub Desktop.
Save joeywhelan/6e7acac5cebb79c7bef93234ffa13190 to your computer and use it in GitHub Desktop.
/*jshint esversion: 6 */
'use strict';
'use esversion 6';
const MongoClient = require('mongodb').MongoClient;
const CONNECTION_URL = 'mongodb://admin:mongo@localhost:27017';
const DB_NAME = 'testDB';
const COLLECTION = 'testCollection';
let connection;
let promises = [];
function updateWithRetry(i, db, query, value, upsrt) {
return db.collection(COLLECTION).updateOne(query, value, {'upsert' : upsrt})
.then((result) => {
return new Promise((resolve, reject) => { resolve('i: ' + i + ' time: ' + new Date().getTime());});
})
.catch(err => {
if (err.code === 11000){
console.log('i: ' + i + ' 11000 error');
return updateWithRetry(i, db, query, value, false);
}
else {
throw err;
}
});
}
function update(i, db, query, value, upsrt) {
return db.collection(COLLECTION).updateOne(query, value, {'upsert' : upsrt})
.then((result) => {
return new Promise((resolve, reject) => { resolve('i: ' + i + ' time: ' + new Date().getTime());});
})
.catch(err => {
throw err;
});
}
MongoClient.connect(CONNECTION_URL, {useNewUrlParser : true})
.then((result) => {
connection = result;
const db = connection.db(DB_NAME);
for (let i=0; i<5; i++) {
let query = {'_id': 'johnDoe'};
let value = { $set : {'funds' : i*100}, $addToSet : {'indices' : i}};
let p = updateWithRetry(i, db, query, value, true);
promises.push(p);
}
return Promise.all(promises);
})
.then((results) => {
results.forEach((result) => {
console.log('result - ' + result);
});
})
.catch(err => {
console.log(err);
})
.finally(() => {
console.log('closing db connection');
connection.close();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment