Sequelize增量函数返回错误

编程入门 行业动态 更新时间:2024-10-27 12:35:06
本文介绍了Sequelize增量函数返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

试图在我的数据库中的模型实例上增加一个整数字段.这是相关的代码.

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

github/sequelize/sequelize/blob/3e5b8772ef75169685fc96024366bca9958fee63/lib/instance.js#L934

但是,当我尝试运行 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增量函数返回错误

本文发布于:2023-10-25 14:32:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527231.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增量   函数   错误   Sequelize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!