Meteor:如何对会话变量进行排序?

时间:2013-06-27 05:29:05

标签: javascript mongodb meteor

我想编写一个帮助方法,该方法返回在个人资料文档的子字段中排序的基于帐户的Facebook列表。帮助器应该依赖两个会话变量来指定子字段和排序顺序。可以通过UI更新会话变量,从而使列表以新顺序重新呈现。类似的东西:

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

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

使用Session.get('sortby')作为属性名称会产生错误。所以问题是,如何使用会话变量来指定排序字段名称?

2 个答案:

答案 0 :(得分:4)

初始化一个Object并将键和值关联到它。然后将其传递给查询。 E.g:

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

但请在分配之前验证它是否未定义:)

答案 1 :(得分:0)

直接在排序说明符中放置Session.get('sortby')会产生语法错误。

在查询之前使用if-else块来找出Session包含的值,并将该字段名称放在查询中而不是Session.get()中:

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