tro*_*oyz 7 node.js sequelize.js
我正在尝试使用以下代码更新Sequelize中的模型:
exports.updateItem = function(item) {
return new Promise((fulfill, reject) => {
models.TimesheetItem.update(item,{where: {id: item.id}})
.then(fulfill)
.catch(console.dir);
});
};
Run Code Online (Sandbox Code Playgroud)
其中item是执行models的结果.TimeSheetItem.find()
调用从不执行.then而是将空对象传递给.catch.
我查看了文档,似乎这是更新行的方法,但我无法让它工作.我究竟做错了什么?
谢谢!
pio*_*ias 16
根据文档,该update方法有两个参数 - 第一个values用于执行更新,第二个用于options- 所以在你的情况下这是where子句.如果只想在单个实例上执行更新,则可以通过两种方式执行此操作 - use Model.update()method,可以一次更新此模型的多个实例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 ]
});
Run Code Online (Sandbox Code Playgroud)
当您只想更新单个实例时,第一个选项不是很有用.这就是为什么有可能update()在Sequelize模型实例上执行
let updateValues = { name: 'changed name' };
instance.update(updateValues).then((self) => {
// here self is your instance, but updated
});
Run Code Online (Sandbox Code Playgroud)
在您的情况下,如果item参数是Sequelize模型实例(不是普通的javascript JSON对象),您的更新功能可能就像那样
exports.updateItem = function(item){
return item.update(values).then((self) => {
return self;
}).catch(e => {
console.log(e);
});
};
Run Code Online (Sandbox Code Playgroud)
但是,如果item它不是一个sequelize模型实例,而只是一个具有你想要更新的值的普通对象,它可以通过两种方式完成 - 首先是使用Model.update()(就像你一样),或者第二种是TimesheetItem使用id = item.id然后检索instance.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);
});
};
Run Code Online (Sandbox Code Playgroud)
或者返回实例并对其执行更新的第二个选项
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);
});
}
Run Code Online (Sandbox Code Playgroud)
不同之处在于您不需要创建并返回自己的Promise- 续集方法,例如update()返回承诺.
| 归档时间: |
|
| 查看次数: |
19041 次 |
| 最近记录: |