I've got an Express application that's using Mongoose/MongoDB and am hoping to find the most efficient way to create/update in bulk (all in a single database operation if possible?).
Users upload a CSV on the frontend that is converted to a JSON array of objects and sent to an Express backend. The array ranges anywhere from ~3000 entries to upwards of ~50,000 and is often a combination of new entries that need to be created as well as existing entries that need to be updated. Each entry is called a Deal.
Here is my current (not very performant) solution:
const deals = [
{ deal_id: '887713', foo: 'data', bar: 'data' },
{ deal_id: '922257', foo: 'data', bar: 'data' }
] // each deal contains 5 key/value pairs in the real data array
const len = deals.length
const Model = models.Deal
let created = 0
let updated = 0
let errors = 0
for (let i = 0; i < len; i++) {
const deal = deals[i]
const exists = await Model.findOne({ deal_id: deal.deal_id })
if (exists) {
exists.foo = deal.foo
exists.bar = deal.bar
await exists.save()
updated += 1
} else {
try {
await Model.create(deal)
created += 1
} catch (e) {
errors += 1
}
}
}
Currently the combination of findOne/save or findOne/create is taking approximately 200-300ms for every Deal. For the low end of 3000 entries, that results in 10-15 minutes to process.
I'm not impartial to circumventing Mongoose and using Mongo directly if that helps.
If possible, I'd like maintain the ability to count the number items that were updated and created as well as the number of errors (this is sent in the response to offer users some feeling of what was successful and what failed) - but this is not critical.
Thanks in advance! :)