I have a Book model that has the property upVotes. Book instances can be queried from the database (MongoDB), modified, and then saved. If a user upvotes a book, I update the upVotes count, and save the whole model back to the server.
The problem is that if someone else votes between the time the instance is loaded, and the time the instance is saved, then the two votes will be saved as just one vote. What I need is an easy way to say “increment the model by 1 server-side”, instead of “increment the model by 1 client-side and hope there will be no conflict”.
You don’t have to save the whole model to the server just to change one thing, you can (and should in this case) add an
upVotemethod to your model that does an “increment upvotes” AJAX call to your server. In your model you’d have something like this:And then the view would have this to handle the upvote action:
and you’d probably have a listener for change events on the model’s
upVotesproperty to properly increment the displayed upvote counter (if you have such a thing).Furthermore, your
/some/upvote/pathon the server would just send an$incupdate into MongoDB to avoid the same “two things happening at once” problem on your server. If you were using a relational database, you’d want to end up doing something likeupdate t set upvotes = upvotes + 1 where id = ?.There is no need for a “query, update, save” round trip on either the client or the server for a simple increment operation. Instead, treat the increment as a single increment operation and push that increment all the way down to your final persistent data storage layer.