Node.js 续集更新
我正在尝试使用以下代码更新Sequelize中的模型:Node.js 续集更新,node.js,sequelize.js,Node.js,Sequelize.js,我正在尝试使用以下代码更新Sequelize中的模型: exports.updateItem = function(item) { return new Promise((fulfill, reject) => { models.TimesheetItem.update(item,{where: {id: item.id}}) .then(fulfill)
exports.updateItem = function(item) {
return new Promise((fulfill, reject) => {
models.TimesheetItem.update(item,{where: {id: item.id}})
.then(fulfill)
.catch(console.dir);
});
};
其中item是执行models.TimeSheetItem.find()的结果
调用从不执行.then,而是将空对象传递给.catch
我查看了文档,似乎这是更新行的方法,但我无法让它工作。我做错了什么
谢谢大家! 根据文档,该方法采用两个参数-第一个是将用于执行更新的
值,第二个是选项
-因此在您的情况下,这是where
子句。如果您只想在单个实例上执行更新,可以通过两种方式执行—使用Model.update()
方法,该方法可以一次更新与where
子句匹配的此模型的多个实例,或者执行instance.update()
以仅更新单个实例。第一个选项如下所示:
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 ]
});
当您只想更新单个实例时,第一个选项不是很有用。所以这就是为什么有可能对Sequelize模型实例执行update()
let updateValues = { name: 'changed name' };
instance.update(updateValues).then((self) => {
// here self is your instance, but updated
});
在您的例子中,如果项
参数是Sequelize模型实例(而不是普通的javascript JSON对象),那么更新函数可能是这样的
exports.updateItem = function(item){
return item.update(values).then((self) => {
return self;
}).catch(e => {
console.log(e);
});
};
但是,如果项
不是一个sequelize模型实例,而只是一个带有您要更新的值的普通对象,那么可以通过两种方法来完成—第一种方法是使用model.update()
(与您一样),第二种方法是使用id=item.id
检索时间表
,然后执行实例.update()
如上所示
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);
});
};
或者返回实例并对其执行更新的第二个选项
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);
});
}
不同之处在于,您不需要创建并返回自己的Promise
-sequelize方法,如update()
自行返回承诺
{ error: type "where" does not exist}
Sequelize只是对解决方案的一个更新,当您包含“where”选项(如下所示)时,它会给出上述错误。所以,把它拿出来,它应该工作得很好
exports.updateItem = function(item){
models.TimesheetItem.update(item, { 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);
});
};
回答得很好,你解释得很好。非常感谢!您没有添加where子句{where:{id:args.id}}
,只添加了{id:args.id}