0

I have a code that updates the number of views on a particular post.

I did it like this:

models.Blog.findById(id).then(blog => {
    models.Blog.update({views: blog.views+1}, {where: {id: blog.id}}).then(blog => {
        //result
   })
})

But if two user tries to update that model at once then there will be race condition.

My question is how to do the same thing and avoid race condition.

JBoy
  • 144
  • 2
  • 17
  • 1
    Possible duplicate of [How to lock table in sequelize, wait until another request to be complete](https://stackoverflow.com/questions/48297419/how-to-lock-table-in-sequelize-wait-until-another-request-to-be-complete) – hgiasac Aug 02 '18 at 18:47
  • I'm sorry i couldn't get it with that article. – JBoy Aug 02 '18 at 20:34

1 Answers1

1

Instead of that , try the below way :

models.Blog.update({ views: Sequelize.literal('views + 2') }, { where: { id: blog.id }}));

This will solve your race condition.

For More : Do Read

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • Please what happens behind the scene? Does it update the views field without fetching the data first? – JBoy Aug 03 '18 at 10:33
  • 1
    It will update field y its latest value , in your case it fetches data from query and then from query data you are updating it , it might take some time, but this will execute single query. – Vivek Doshi Aug 03 '18 at 10:50