[英]Meteor: How can I sort a collection on a session variable?
我想编写一个帮助程序方法,该方法返回在配置文件文档的子字段上排序的基于accounts-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')
作为属性名称会产生错误。 所以问题是,如何使用会话变量指定排序字段名称?
初始化一个对象,并将键和值关联到它。 然后将其传递给查询。 例如:
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')}});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.