How to replace the Key for sort field in a meteor collection query?

随声附和 提交于 2019-12-23 01:20:08

问题


In the code below, I want to replace the name key with a value being passed in via a parameter this.params.sortby but I can't get it working. Looking for some help.

So if:

this.params.sortby=location

I want this:

Template.MyTemplate.helpers({
    data: function () {
      return MyCollection.find({},{sort:{name: 1 }});
    }
  });

To become this:

Template.MyTemplate.helpers({
    data: function () {
      return MyCollection.find({},{sort:{location: 1 }});
    }
  });

回答1:


You can use an object with the bracket notation to achieve dynamic key naming, like this :

var sorter={};
sorter[this.params.sortby]=1;

Assuming that this.params.sortby is equal to the String "age", you'd have the following sorter object :

var sorter={
  age:1
};

Then you can use to sort your collection appropriately :

MyCollection.find({},{sort:sorter});



回答2:


Make a SORT factory builder to generate sort criteria before query.



来源:https://stackoverflow.com/questions/25656151/how-to-replace-the-key-for-sort-field-in-a-meteor-collection-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!