javascript - Mongoose Variable Sort - Stack Overflow

I want to sort based on a variable the user enters. I have something like this:var find = Record.find(q

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?

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?

Share Improve this question asked Oct 16, 2015 at 0:10 KJ3KJ3 5,3184 gold badges37 silver badges54 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

Assuming you're using node v4+, you can use the ES6 enhanced literal syntax support for puted 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);

Figured it out. Can't use the find.sort[sortField] = 1 notation since it's a function, need to do that ahead of time.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744604507a4583382.html

相关推荐

  • javascript - Mongoose Variable Sort - Stack Overflow

    I want to sort based on a variable the user enters. I have something like this:var find = Record.find(q

    2天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信