好的,这是一个有趣的。我正在对 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);
}
});
});
另外,我是新手,所以对于任何明显的格式错误,我深表歉意,如果您觉得有必要,请指出。谢谢!