【问题标题】:Upvoting and downvoting posts - Meteor赞成和反对的帖子 - Meteor
【发布时间】: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


    【解决方案1】:

    您必须获取帖子并查看其downvoters 数组中是否包含用户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
          }
        }
      });
    }
    

    【讨论】:

    • 非常感谢!像魅力一样工作
    猜你喜欢
    • 2019-03-10
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    相关资源
    最近更新 更多