Search code examples
node.jssequelize.jsvariable-assignmentadditionsubtraction

Addition and Subtraction Assignment Operator With Sequelize


I would like to do an update by doing a simple addition on Sequelize.

table:

id || data
 1 ||  10 

sample:

db.table.update({ data : 1 }, { where: { id: 1 }});

after this query

id || data
 1 ||  11

I know it's a simple question, but I could not find the solution.

Which operator can I add and subtract? Thank you


Solution

  • Here it is :

    db.table.update({ field: Sequelize.literal('data + 1') }, { where: { id: 1 }}))
    

    OR

    User.findById(1).then(user => {
      // -----> First Way
      return user.increment('my-integer-field', {by: 2});
      // -----> Second Way
      return user.increment([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
      // -----> Third Way
      return user.increment({
         'my-integer-field':    2,
         'my-very-other-field': 3
      })
    });
    

    You can also do decrement by just replacing increment with decrement.


    For Version6 :

    await User.increment({age: 5}, { where: { id: 1 } }) // Will increase age to 15
    await User.increment({age: -5}, { where: { id: 1 } }) // Will decrease age to 5
    

    For more detail : DO READ