Sequelize update
According to the documentation the update
method takes two parameters - first one is values
which will be used to perform the update, and second one is options
- so in your case this is the where
clause. If you want to perform an update on a single instance only, you can do it in two ways - use Model.update()
method, which can update multiple instances of this model at once matching the where
clause, or perform instance.update()
in order to update only the single instance. First option will look like that:
let updateValues = { name: 'changed name' };
models.Model.update(updateValues, { where: { id: 1 } }).then((result) => {
// here your result is simply an array with number of affected rows
console.log(result);
// [ 1 ]
});
The first option is not very useful when you want to update only single instance. So that is why there is a possibility of performing update()
on Sequelize model instance
let updateValues = { name: 'changed name' };
instance.update(updateValues).then((self) => {
// here self is your instance, but updated
});
In your case, if the item
parameter is a Sequelize model instance (not a plain javascript JSON object), your update function could be like that
exports.updateItem = function(item){
return item.update(values).then((self) => {
return self;
}).catch(e => {
console.log(e);
});
};
However, if the item
is not a sequelize model instance but only a plain object with values you want to update, it could be done in two ways - first is to use Model.update()
(just like you did), or second one is to retrieve TimesheetItem
with id = item.id
and then perform instance.update()
as shown above
exports.updateItem = function(item){
models.TimesheetItem.update(item, { where: { id: item.id } }).then((result) => {
// here result will be [ 1 ], if the id column is unique in your table
// the problem is that you can't return updated instance, you would have to retrieve it from database once again
return result;
}).catch(e => {
console.log(e);
});
};
Or the second option with returning instance and performing update on it
exports.updateItem = function(item) {
return models.TimesheetItem.findById(item.id).then((itemInstance) => {
return itemIstance.update(item).then((self) => {
return self;
});
}).catch(e => {
console.log(e);
});
}
The difference is that you do not need to create and return your own Promise
- sequelize methods like update()
return promises by themselves.