Moving and descending posts - Meteor

Up and downvotes are functional, but I would like to do a check like "If the user is downvoter or upvoter" and does the right thing, which is explained below

upvote: function(postId) {    
    check(this.userId, String);    
    check(postId, String);
    var affected = Posts.update({      
        _id: postId,       
        upvoters: {$ne: this.userId}
    },{ 
        $addToSet: {
            upvoters: this.userId
        },  
        $inc: {
            upvotes: 1
        }
    });

    if (! affected)      
        throw new Meteor.Error('invalid', "You already up-voted this post");
},

downvote: function(postId) {    
    check(this.userId, String);    
    check(postId, String);
    var affected = Posts.update({      
        _id: postId,       
        downvoters: {$ne: this.userId},
    }, {      
        $addToSet: {
            downvoters: this.userId
        },  
        $inc: {
            downvotes: 1
        }
    });

    if (! affected)      
        throw new Meteor.Error('invalid', "You already down-voted this post");     
},

      

With my code above, users can upgrade and demote once, but they can do both ...

I wrote some code for what happens if the user is downvoter and presses upvote, but I couldn't figure out how to check if the user is downvoter or upvoter.

$pull: {
        downvoters: this.userId
    },
$addToSet: {
        upvoters: this.userId
    },  
    $inc: {
        downvotes: -1
    },
    $inc: {
        upvotes: 1
});

      

EDIT: Even though the accepted answer works fine, I found a problem with it. When you hit fast, it can increase the number of votes 2-3 times. Instead of increasing the number of votes, I insert userId and just count how many ids there are inside the upvoters / downvoters array, which gives the same result, and it never inserts the same user ID twice.

Inside the counting helpers:

return this.upvoters.length

      

Also, inArray is a useful tool for checking if a value is inside an array.

if($.inArray(Meteor.userId(), this.upvoters)) //gives true if the current user ID is inside the array

      

+3


source to share


1 answer


You will need to get the message and see if it contains the user id in an array downvoters

:



var post = Posts.findOne(postId);
if (post.downvoters && _.contains(post.downvoters, this.userId)) {
  Posts.update({      
      _id: postId
    },
    {
      $pull: {
        downvoters: this.userId
      },
      $addToSet: {
        upvoters: this.userId
      },  
      $inc: {
        downvotes: -1,
        upvotes: 1
      }
    }
  });
}

      

+4


source







All Articles