Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Variable Sort

I want to sort based on a variable the user enters. I have something like this:

var find = Record.find(query);

The following works just fine:

find.sort({age: 1});

It sorts by age. I want to do the following:

find.sort({sortField: 1});

I've tried this as well:

find.sort[sortField] = 1;

To no luck. Any way to set sort with a string variable passed in?

like image 567
KJ3 Avatar asked Sep 20 '26 05:09

KJ3


1 Answers

Assuming you're using node v4+, you can use the ES6 enhanced literal syntax support for computed property names:

find.sort({[sortField]: 1});

Otherwise you need to create your sort object in a couple steps:

var sort = {};
sort[sortField] = 1;
find.sort(sort);
like image 122
JohnnyHK Avatar answered Sep 22 '26 19:09

JohnnyHK