Sequelize增量函数返回错误 [英] Sequelize increment function returning error
问题描述
试图在我的数据库中的模型实例上增加一个整数字段.这是相关的代码.
Trying to increment an integer field on a model instance in my DB. Here is the relevant code.
models.Options.findAll({
where: {
PollId: poll_id,
name: option_to_update
}
}).then((option) => {
option.increment('votes');
res.json(option);
});
当我使用 console.log(option) 时,它显示为一个 Instance,所以我知道它继承自 Instance 类,该类具有增量函数,如下所示
When I console.log(option), it shows as an Instance so I know it inherits from the Instance class which has an increment function as can be seen here
但是,当我尝试运行 option.increment 时,我得到了这个
However, when I try to run option.increment, I get this back
未处理的拒绝类型错误:option.increment 不是函数
Unhandled rejection TypeError: option.increment is not a function
不太确定我做错了什么.
Not really sure what I'm doing wrong.
推荐答案
findAll()
会返回一个结果数组,所以如果你想增加字段,你应该使用 option[0].increment('votes')
(假设您只想更新第一个结果).
findAll()
will return an array of results, so if you want to increment the field, you should use option[0].increment('votes')
(assuming you want to update only the first result).
或者,如果您知道最多只有一个结果,您可以使用 findOne
而不是 findAll
.
Or, if you know there's going to be at most one result, you could use findOne
instead of findAll
.
由于增量完全是服务器端完成的,如果要在增量后检索数据库中文档的当前版本,则需要 先重新加载实例.
Because incrementing is done entirely server side, if you want to retrieve the current version of the document in the database after incrementing, you need to reload the instance first.
我认为这样做是合适的方式:
I think this would be the appropriate way of doing that:
models.Options.findOne({
where: {
PollId: poll_id,
name: option_to_update
}
}).then(option => {
return option.increment('votes'); // assumes `option` always exists
}).then(option => {
return option.reload();
}).then(option => {
res.json(option);
});
(当然,您可以走捷径并假设 votes
在递增后将是其当前值 + 1,但在高度并发的情况下可能并非总是如此)
(of course, you could take a shortcut and assume that votes
will be its current value + 1 after incrementing, but in a highly concurrent situation that might not always be the case)
这篇关于Sequelize增量函数返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!