问题描述
尝试在我的数据库中的模型实例上增加一个整数字段。这是相关的代码。
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)时,它显示为一个实例,所以我知道它是从可以在此处看到具有增量功能的实例类
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
不太确定我在做什么错。
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).
或者,如果您知道最多会有一个结果,则可以使用而不是 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.
我认为
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);
});
(当然,您可以采取捷径并假设投票
将是它的当前值+递增后的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)
这篇关于序列化增量函数返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!