timmyg13
timmyg13

Reputation: 503

Mongo sort by dynamic field

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;
}

Upvotes: 9

Views: 5713

Answers (2)

Vishal Patel
Vishal Patel

Reputation: 1745

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}
  });

Upvotes: 11

David Weldon
David Weldon

Reputation: 64342

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
  });
};

Upvotes: 18

Related Questions