From the docs, you don’t need to query where
to perform the update once you have the object. Also, the use of promise should simplify callbacks:
Implementation
function upsert(values, condition) {
return Model
.findOne({ where: condition })
.then(function(obj) {
// update
if(obj)
return obj.update(values);
// insert
return Model.create(values);
})
}
Usage
upsert({ first_name: 'Taku' }, { id: 1234 }).then(function(result){
res.status(200).send({success: true});
});
Note
- This operation is not atomic.
- Creates 2 network calls.
which means it is advisable to re-think the approach and probably just update values in one network call and either:
- Look at the value returned (i.e. rows_affected) and decide what to do.
- Return success if update operation succeeds. This is because whether the resource exists is not within this service’s responsibility.