Skip to content

Instantly share code, notes, and snippets.

@akshendra
Created April 17, 2018 06:06
Show Gist options
  • Save akshendra/43a993f31167adcc8df3ef831b32a40a to your computer and use it in GitHub Desktop.
Save akshendra/43a993f31167adcc8df3ef831b32a40a to your computer and use it in GitHub Desktop.
mongo bulk insert
function updateOrUpsertMany(mongo, col, docs) {
const bulk = mongo.colection(col).initializeUnorderedBulkOp();
docs.forEach(doc => {
bulk.find({ _id: doc._id }).upsert().updateOne({ $set: doc });
});
if (docs.length > 0) {
return bulk.execute()
.catch((ex) => {
if (ex.message.indexOf('E11000 duplicate key error collection') !== -1) {
return this.updateOrUpsertMany(mongo, col, docs);
}
throw ex;
});
}
const error = new Error('Noting to insert');
return Promise.reject(error);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment