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.

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Please what happens behind the scene? Does it update the views field without fetching the data first?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.