Last active
January 20, 2019 16:08
-
-
Save joeywhelan/6e7acac5cebb79c7bef93234ffa13190 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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
https://joeywhelan.blogspot.com/2019/01/mongodb-e11000-duplicate-key-error.html