Meteor:如何在会话变量上对集合进行排序

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

本文关键字:集合 排序 变量 会话 Meteor      更新时间:2023-09-26

我想写一个helper方法,它返回一个基于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')作为属性名称会产生错误。所以问题是,如何使用会话变量来指定排序字段名称?

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

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

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

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