kdipaolo
kdipaolo

Reputation: 101

Custom Sorting in Meteor

I'm basically trying to create my own ranking system and wanting to display users based off the highest ranked user to the lowest ranked user. For example lets say I have a user collection:

{_id: "CwqaMwgyRNa3G99HD", createdAd: Fri Oct 30, profile: {...}},
{_id: "AcqaMwgyRNa3G99HD", createdAd: Fri Oct 30, profile: {...}},
{_id: "hrqaMwgyRNa3G99HD", createdAd: Fri Oct 30, profile: {...}},
{_id: "DsfaMwgyRNa3G99HD", createdAd: Fri Oct 30, profile: {...}},
{_id: "fdsqaMwgyRNa3G99HD", createdAd: Fri Oct 30, profile: {...}}

I want to be able to write a function and rank the above users and ideally go through those users and add a ranking property (on the client side) based on a function. For example:

if(Meteor.user.profile.name == "Bob"){
  // Add 5 to the rank property
}else if(Meteor.user.profile.job == "Business Man"){
  // Add 5 more to the rank property    
}

// Now users have rank property added to them based on the function above
{_id: "CwqaMwgyRNa3G99HD",rank: 5, createdAd: Fri Oct 30, profile: {...}},
{_id: "AcqaMwgyRNa3G99HD", rank: 10, createdAd: Fri Oct 30, profile: {...}},
{_id: "hrqaMwgyRNa3G99HD", rank: 5, createdAd: Fri Oct 30, profile: {...}},
{_id: "DsfaMwgyRNa3G99HD", createdAd: Fri Oct 30, profile: {...}},
{_id: "fdsqaMwgyRNa3G99HD", createdAd: Fri Oct 30, profile: {...}}

I lastly then want to display the users on the client side with the highest rank first. So ideally the ID with a rank of 10 would show then the two with a rank of 5 and then the rest. Any idea of how to do this? I would ideally like this to be done on the client side because I just need this to be shown on the client and not stored in mongo. Would I used a session for this? If so, I'm not quite sure how to do a session like that. Thanks for your help!

Upvotes: 0

Views: 226

Answers (1)

bluebird
bluebird

Reputation: 640

You could try using the collection.forEach method to compute the rankings and the _.sortBy to sort the resulting docs.

So for example you could define a template helper like so:

Template.rankings.helpers({
  user: function() { 
    var rankings = [];
    var sorted;

    Meteor.users.find().forEach(function(user, index) {
      var rank = 0;
      if(user.profile.name == "Bob"){
        rank = rank + 5;
      }
       if(user.profile.job == "Business Man"){
        // Add 5 more to the rank property    
        rank = rank + 5
      } 
      user.rank = rank;
      rankings.push(user); 
    }):

    sorted = _.sortBy(rankings, rank);
    return sorted;

   }
});

And then iterate over the sorted list in your template like so:

<template name="rankings">
  {{#each user}} 
    {{rank}}, {{profile.name}}, {{profile.job}}
  {{/each}}
</template>

Upvotes: 1

Related Questions