【问题标题】:Meteor: How can I sort a collection on a session variable?Meteor:如何对会话变量的集合进行排序?
【发布时间】:2013-06-27 22:06:06
【问题描述】:

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

【问题讨论】:

  • 您是否尝试将 Session.get('sortorder') 转换为整数?
  • ` Meteor.users.find({}, {sort:{Session.get('sortby'):+Session.get('sortorder')}}); `
  • 您遇到了哪个错误?你能发布那个错误跟踪吗?
  • 错误在 Session.get('sortby') 上。编译器声称点字符在那里是非法的。

标签: javascript mongodb meteor


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-07
      • 2013-12-24
      • 2011-04-04
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多