Avoiding race condition with Nodejs Sequelize

无人久伴 提交于 2019-12-11 15:15:40

问题


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.


回答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



来源:https://stackoverflow.com/questions/51660205/avoiding-race-condition-with-nodejs-sequelize

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