【发布时间】:2016-02-22 10:05:02
【问题描述】:
赞成和反对票是有效的,但我想做一个检查,比如“如果用户是反对票或反对票”,并做正确的事情,如下所述
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 并简单地计算 upvoters/downvoters 数组中有多少个 ID,它给出了相同的结果并且它从不插入相同的 userId 两次。
在计数的助手内部:
return this.upvoters.length
此外,inArray 是一个有用的工具,用于检查您拥有的值是否在数组中。
if($.inArray(Meteor.userId(), this.upvoters)) //gives true if the current user's ID is inside the array
【问题讨论】:
标签: meteor