简体   繁体   中英

Meteor: How can I sort a collection on a session variable?

I want to write a helper method that returns a list of accounts-facebook based user profiles sorted on a sub-field of the profile document. The helper should rely on two session variables to specify the sub-field and order to sort on. The session variables can be updated via the UI, causing the list to re-render in the new order. Something like:

Session.set('sortby', "profile.email");
Session.set('sortorder', "-1");

Template.userlist.users = function() {
   Meteor.users.find({}, {sort:{Session.get('sortby'):Session.get('sortorder')}});
}

Using Session.get('sortby') as the property name produces an error though. So the question is, how can I use a session variable to specify the sort field name?

Initialize an Object and associate the key and value to it. Then pass it to the query. Eg:

var filter = {sort: {}};
filter.sort[Session.get('sortby')] = Session.get('sortorder');
Meteor.users.find({}, filter);

But please, verify if it's undefined before assigning it :)

Placing Session.get('sortby') directly in sort specifier will give a syntax error.

Use an if-else block before the query to find out which value the Session contains, and put that field-name in query instead of Session.get() like:

if( Session.equals('sortBy', 'profile_email') ){
   return  Meteor.users.find({}, {sort:{'profile_email':Session.get('sortorder')}});
} 
else if( Session.equals('sortBy', 'other_value') ) {
   return  Meteor.users.find({}, {sort:{'other_value':Session.get('sortorder')}});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM