Sequelize increment function returning error

北战南征 提交于 2020-01-04 05:22:18

问题


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);
    });

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

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

However, when I try to run option.increment, I get this back

Unhandled rejection TypeError: option.increment is not a function

Not really sure what I'm doing wrong.


回答1:


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).

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);
});

(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)



来源:https://stackoverflow.com/questions/44104860/sequelize-increment-function-returning-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!