Organizational Research By

Surprising Reserch Topic

voting system with backbone js

voting system with backbone js  using -'mongodb,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".

asked Oct 13, 2015 by rajnipancholi
0 votes
1 view

Related Hot Questions

1 Answer

0 votes

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

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.

answered Oct 13, 2015 by sumit_jaiswalmca