Skip to content

Instantly share code, notes, and snippets.

@armand1m
Created October 18, 2016 14:22
Show Gist options
  • Save armand1m/b2bd6b551d3c1f2b7254bcb339c0d869 to your computer and use it in GitHub Desktop.
Save armand1m/b2bd6b551d3c1f2b7254bcb339c0d869 to your computer and use it in GitHub Desktop.
A bulkUpsert function using Promises and the Sequelize API
module.exports = function bulkUpsert(model, key, values) {
function _find(where) {
return model.findOne({ where })
}
function _update(value, where) {
return model
.update(value, { where })
.then(() => _find(where))
}
let promises =
values.map(value => {
let where = {
[key]: value[key]
}
return model
.findOrCreate({ where, defaults: value })
.spread((result, created) => {
return (!created)
? _update(value, where)
: Promise.resolve(result)
})
})
return Promise.all(promises)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment