使用 Nodejs Sequelize 避免竞争条件 [英] Avoiding race condition with Nodejs Sequelize

查看:40
本文介绍了使用 Nodejs Sequelize 避免竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码可以更新特定帖子的查看次数.

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

我是这样做的:

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.

推荐答案

改为尝试以下方式:

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

这将解决您的竞争条件.

This will solve your race condition.

更多:请阅读

For More : Do Read

这篇关于使用 Nodejs Sequelize 避免竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆