尝试增加我的数据库中模型实例的整数字段。这是相关代码。
models.Options.findAll({
where: {
PollId: poll_id,
name: option_to_update
}
}).then((option) => {
option.increment('votes');
res.json(option);
});
当我 console.log(option) 时,它显示为一个 Instance,所以我知道它继承自 Instance 类,该类具有增量函数,如下所示
https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L934 https://github.com/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L934
但是,当我尝试运行 option.increment 时,我得到了这个
未处理的拒绝 TypeError: option.increment 不是函数
不太确定我做错了什么。
findAll()
将返回一个结果数组,因此如果您想增加该字段,您应该使用option[0].increment('votes')
(假设您只想更新第一个结果)。
或者,如果您知道最多会有一个结果,您可以使用findOne http://sequelize.readthedocs.io/en/latest/api/model/#findoneoptions-promiseinstance代替findAll
.
因为增量完全是在服务器端完成的,所以如果您想在增量后检索数据库中文档的当前版本,您需要reload http://sequelize.readthedocs.io/en/latest/api/instance/#reload首先是实例。
我认为这将是这样做的适当方式:
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,但在高度并发的情况下,情况可能并不总是如此)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)