提问者:小点点

上投和下投帖子-流星


赞成和反对投票是有效的,但我想做一个检查,比如“如果用户是反对者还是反对者”,并做正确的事情,如下所述

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");     
},

使用我上面的代码,用户可以支持和反对一次,但他们可以两者兼而有之……

我编写了如果用户是向下投票并单击向上投票会发生什么的代码,但我不知道如何检查用户是向下投票还是向上投票。

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

编辑:即使被接受的答案工作正常,我发现它有一个问题。当你点击快速时,它可能会增加2-3次投票计数。我没有增加投票计数,而是只插入userId并简单地计算给出相同结果的上选者/下选者数组中有多少ID

在伯爵的助手里面:

return this.upvoters.length

此外,inArray是一个有用的工具,用于检查您拥有的值是否在数组中。

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

共1个答案

匿名用户

您必须获取该帖子并查看它是否在其down人数组中包含用户的id:

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
      }
    }
  });
}