多个用户没有收到Meteor方法调用的结果 - 工作一次,然后返回undefined?

时间:2017-04-12 13:25:56

标签: reactjs meteor meteor-methods

好的,这是一个有趣的。我正在排序Meteor中的用户列表,并尝试将用户的索引号返回给客户端。即我希望创建的第一个用户是位置1,第二个用户创建为位置2,第三个用户位置3等。

我在服务器上使用Meteor方法:

Meteor.methods({
  setPosition: function(userId) {
    let usersArray = Meteor.users.find({}, {sort: {createdAt: 1}}).fetch();
    if (!this.userId) {
      throw new Meteor.Error('not-authorized');
    }
    let pos = [];
    for (i = 0; i < usersArray.length; i ++) {
      if (usersArray[i]._id === this.userId) {
         pos = i + 1;
       }
         console.log('this is the position', pos);
         return pos;
     };
    }
  }); //Meteor methods
}//end of meteor isServer

上面的服务器代码在终端中完美地工作除了“返回pos”行,这使得代码将值传递给第一个用户的客户端(我看到位置1),但是为后续用户打破了(res未定义)。如果我删除“返回pos”行,那么代码在服务器上完全适用于所有用户,但是我无法通过客户端上的Meteor方法调用获得单个结果

以下客户端代码无法从服务器上的Method调用接收结果,我不知道原因:

Tracker.autorun(() => {
  Meteor.subscribe('position');
    Meteor.call('setPosition', Meteor.userId(), (err, res) => {
      if (err) {
        throw new Meteor.Error(err.message);
        console.log(err);
      } else {
        console.log(res);
        console.log(Meteor.userId());
        Session.set('position', res);
      }
    });
});

另外,我是一个新手,所以我为任何明显的格式错误道歉,请指出你是否觉得有必要。谢谢!

1 个答案:

答案 0 :(得分:1)

我们只是说这种方法不太可能扩展得很好,因为您拥有的用户越多,找到用户位置的时间越长在用户列表中。

假设用户的位置永远不会改变(即你不关心删除 - 即使#3被删除,第4位用户总是第4位),你最好还是添加一个用户创建时用户对象的sequence键。您可以查看最近创建的用户的序列号,并将其增加一个以将其提供给下一个用户。您当然希望将该密钥编入索引。然后每个用户只需Meteor.user().sequence

即可知道他们的序列号