Created
April 17, 2018 06:06
-
-
Save akshendra/43a993f31167adcc8df3ef831b32a40a to your computer and use it in GitHub Desktop.
mongo bulk insert
This file contains hidden or 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
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