redixhumayun
redixhumayun

Reputation: 1844

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

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.

Upvotes: 3

Views: 5898

Answers (1)

robertklep
robertklep

Reputation: 203359

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)

Upvotes: 4

Related Questions