reactjsmeteormeteor-methods

multiple users not receiving result from Meteor method call - works once, then returns undefined?


Ok this is an interesting one. I am sorting a list of users in Meteor and trying to return the index number of the user to the client. i.e. I want the first user created to be position 1, the second user created to be position 2, third user position 3, etc.

I am using a Meteor method on the server:

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

The server code above is working perfectly in the terminal EXCEPT the "return pos" line, which makes the code deliver the value to the client for the first user (I see position 1), but break for the subsequent users (res is undefined). If I remove the "return pos" line, then the code works perfectly on the server for ALL users, but I cannot get a single result from my Meteor method call on the client.

This client code below is having trouble receiving the result from the Method call on the server and I don't know why:

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

Also, I'm a newb so I apologize for any obvious formatting errors, please point out if you feel the need. Thank you!


Solution

  • Let's just say that this approach is unlikely to scale well as the more users you have the longer it's going to take to find a user's position in the list of users.

    Assuming that a user's position never changes (i.e. you don't care about deletions - the 4th user is always 4th even if #3 gets deleted), you'd be better off adding a sequence key to the user object on user creation. You can look at the sequence number of the most recently created user and increment that by one to give it to the next user. You'll want that key to be indexed of course. Then each user can know their sequence number with just Meteor.user().sequence