Up and Downvote button

263 Views Asked by At

I try to achieve an up or downvote button where a user is able to vote just 1 time up and 1 time down. If you already have upvoted something it should be possible to remove that with another click on the upvote button, but i dont know what is missing for this. My code looks like the following. I guess i have to implement something with a true of false statement but i tried some things and nothing worked. I would appreciate your help!

Template.postArgument.events({
 'click':function() {
  Session.set('selected_argument', this._id);
  },
 'click .yes':function() {
          if(Meteor.user()) {
            var postId = Arguments.findOne({_id:this._id})
            console.log(postId);
            if($.inArray(Meteor.userId(), postId.votedUp) !==-1) {
              return "Voted";
            } else {
        var argumentId = Session.get('selected_argument');
        Arguments.update(argumentId, {$inc: {'score': 1 }}); 
        Arguments.update(argumentId, {$addToSet: {votedUp: Meteor.userId()}});
            }
          }
  }});
2

There are 2 best solutions below

1
On BEST ANSWER

Your general approach is correct however you don't need the Session variable at all or even the first click handler. And you don't need to return anything at all from the function.

Template.postArgument.events({
  'click .yes': function(){
    if ( Meteor.user() ) {
      var post = Arguments.findOne({_id:this._id});
      if ( $.inArray(Meteor.userId(), post.votedUp) === -1 ) {
        Arguments.update(this._id, {
          $inc: { score: 1 },
          $addToSet: { votedUp: Meteor.userId() }
        }); 
      } else {
        Arguments.update(this._id, {
          $inc: { score: -1 },
          $pull: { votedUp: Meteor.userId() }
        }); 
      }
    }
  }
});
0
On

You can start simple by checking for the existence of the user in the upvotes and downvotes and increment/decrement accordingly then add the user to the sets.

Meteor.methods({
  'downvote post': function (postId) {
    check(postId, String);
    let post = Posts.findOne(postId);

    Posts.update(postId, post.downvoters.indexOf(this.userId !== -1) ? {
      $inc: { downvotes: -1 },               // remove this user's downvote.
      $pull: { downvoters: this.userId }     // remove this user from downvoters
    } : {
      $inc: { downvotes: 1 },                // add this user's downvote
      $addToSet: { downvoters: this.userId } // add this user to downvoters.
    });
  }
});