Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo sort by dynamic field

Tags:

mongodb

meteor

So I have a dynamic variable being passed in that is the name of the field that I would like to sort on.

Let's say sortVariable below could equal "price", "createdAt", "name" etc. This isn't working, how can I do this?

function findStuff (sortVariable) {
    var postings = Postings.find({
      "device.name": filter.exactDevice,
    }, {
      sort: {
        sortVariable: 1
      }
    });
    return postings;
}
like image 251
timmyg13 Avatar asked Mar 11 '14 03:03

timmyg13


2 Answers

You can't use variables as keys in object literals. Give this a try:

var findStuff = function(sortVariable) {
  var sort = {};
  sort[sortVariable] = 1;

  return Postings.find({
    'device.name': filter.exactDevice
  }, {
    sort: sort
  });
};
like image 129
David Weldon Avatar answered Oct 30 '22 22:10

David Weldon


If you're using node v4, you can use the ES6 syntax:

   find.sort({[sortVariable]: 1});
return Postings.find({
    'device.name': filter.exactDevice
  }, {
    sort: {[sortVariable]: 1}
  });
like image 39
Vishal Patel Avatar answered Oct 31 '22 00:10

Vishal Patel