问题
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