簡體   English   中英

流星:如何對會話變量排序集合?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM