[英]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. 我想编写一个帮助程序方法,该方法返回在配置文件文档的子字段上排序的基于accounts-facebook的用户配置文件的列表。 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.
可以通过UI更新会话变量,从而使列表以新顺序重新呈现。 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. 但是,使用
Session.get('sortby')
作为属性名称会产生错误。 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. 将
Session.get('sortby')
直接放置在排序说明符中将产生语法错误。
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-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.