Dynamic sort field in a query


#1

I have a helper that returns the following:

posts: function() {
   return Posts.find({}, {sort: {createdAt: 1}});
}

I want to change the sort field and the sort direction when an event occurs.
Something along:

'click #posts': function() {
  sort.set('post');
}
'click #name': function() {
  sort.set('name');
}
'click #votes': function() {
  sort.set('vote');
}

   .
   .
   .

 return Posts.find({}, {sort: { "sort.get()": 1}});

This of course does not work.
The straightforward solution would be to use a switch statement with different queries, but that seems kind of ugly.
Any suggestions for a more elegant approach?

cheers,
Godo


#2

try this instead

var sortby = {};

sortBy[sort.get()] = 1

return Posts.find({}, {sort:sortBy});

#3

Well, the idea is correct. You need to do something like this:

var sort = new ReactiveVar({});
var posts = new ReactiveVar();

// On click
sort.set({ createdAt: 1 });

Tracker.autorun(function () {
  posts.set(Posts.find({}, { sort: sort.get() }));
});

// In template helper
return posts.get()

I’m on my phone and couldn’t test it, but it should be enough to get an idea. Hope it helps :blush:


#4

thanks for the fast replies :blush:


#5

So what exactly worked? I’m not sure where to put the tracker, and I’m getting errors if I don’t have random reactive vars and sessions in my events and helper

@fvg @godo15


#7

Apparently you’d use tracker outside the helpers- as those are reactive-, but neither method appears to work. There’s also subscription method that you could run where publish takes parameter of the field, but I doubt that it will really translate into your db.collection.find() helper, although that would be the more to the point method.


#8

Session variable can help you too ! :smiley:


#9


Im guessing you could pick columns to sort with in here


#10


This will work for single variable with session get.