为什么我的$ .inArray()函数在投票系统中不起作用?

mhl*_*cka 1 javascript jquery mongodb meteor

我想允许用户仅支持/关闭投票一次,所以我想检查用户是否已经投票.但问题是我的函数总是说用户已经投票,而MongoDB中没有单个userId投票数组.这是功能:

Template.postItem.events({
    'click': function() {
        Session.set("selected_post", this._id);
    },

    'click a.yes': function(event) {
        if (Meteor.user()) {
            event.preventDefault();
            if ($.inArray(Meteor.userId(), Posts.voted)) {
                console.log('User already voted.');
            } else {
                var postId = Session.get('selected_post');
                console.log("voting" + Meteor.userId());
                Posts.update(postId, {$push: {voted: Meteor.userId()}});
                Posts.update(postId, {$inc: {'score' : 1}});
                }
            }
        }, 
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 6

inArray是一个非常糟糕命名的功能:它返回在该事被发现,或者-1如果它没有被发现,该指数(顾名思义)true如果发现,false如果没有.所以你要

if ($.inArray(Meteor.userId(), Posts.voted) !== -1) {
// ----------------------------------------^^^^^^^
Run Code Online (Sandbox Code Playgroud)

  • 确实`inArray是一个名字很差的函数`:( (2认同)