I have an article model, and a comment model. Each article can have up to 10 comments.
Whenever I add a comment, this check is done in the controller.
Article.findOne({ id: 3 }, function(err, record){
if(record.commentCount < 10){
Comment.create({ /* parameters */ })
}
});
(the code isn't checked, but the important part is that there are two queries here).
Now, since Node.js is run in several threads on several computers, this will definitely result in race condition. If 100 requests are done simultaneously, it's unavoidable that sometime some of them will get the count first simultaneously, and then add the comment because all of them thought that there are less than 10 comments.
How can I fix this? Is there a way to lock the database, or lock a row? Ruby on Rails allows me to do pessimistic locking and fix this problem perfectly.