简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM