0

好的,这是一个有趣的。我正在对 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

上面的服务器代码在终端中完美运行,除了“return pos”行,这使得代码为第一个用户(我看到位置 1)将值传递给客户端,但为后续用户中断(res 未定义) . 如果我删除“return pos”行,那么代码在服务器上对所有用户都可以完美运行,但我无法从客户端上的 Meteor 方法调用中获得单个结果

下面的这个客户端代码无法从服务器上的方法调用中接收结果,我不知道为什么:

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

另外,我是新手,所以对于任何明显的格式错误,我深表歉意,如果您觉得有必要,请指出。谢谢!

4

1 回答 1

1

假设这种方法不太可能很好地扩展,因为您拥有的用户越多,在用户列表中找到用户位置的时间就越长。

假设用户的位置永远不会改变(即您不关心删除 - 第 4 个用户始终是第 4 个,即使 #3 被删除),您最好sequence在用户创建时向用户对象添加一个键。您可以查看最近创建的用户的序列号并将其加一以将其提供给下一个用户。当然,您会希望该键被索引。然后每个用户都可以知道他们的序列号Meteor.user().sequence

于 2017-04-12T19:13:35.420 回答