问题
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