Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Voting system with Backbone.js

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".

like image 441
Randomblue Avatar asked Aug 25 '26 05:08

Randomblue


1 Answers

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 upVote method to your model that does an "increment upvotes" AJAX call to your server. In your model you'd have something like this:

upVote: function() {
    var self = this;
    $.ajax({
        url: '/some/upvote/path',
        type: 'POST',
        success: function(data) {
            self.set('upVotes', data.upVotes);
        },
        // ...
    });
}

And then the view would have this to handle the upvote action:

upVote: function() {
    // Highlight the upvote button or provide some other feedback that
    // the upvote has been seen.
    this.model.upVote();
}

and you'd probably have a listener for change events on the model's upVotes property to properly increment the displayed upvote counter (if you have such a thing).

Furthermore, your /some/upvote/path on the server would just send an $inc update 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 like update 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.

like image 162
mu is too short Avatar answered Aug 30 '26 10:08

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!