Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sort in MongooseJS 3.3.1 in ascending and descending order

Sort in MongooseJS 3.3.1 in ascending and descending order

Problem

I have REST based API in NodeJS and MongooseJS ODM. To GET the list of departments URL is http://localhost:25718/Department?SortBy=Name&SortType=asc(desc-for descending). And sorting code is

 var Query = Department.find();
 if(req.query.SortBy) {
        Query.sort(req.query.SortBy, 1);
        if(req.query.SortType) {
            if(req.query.SortType.toLowerCase() == 'desc') {
                Query.sort(req.query.SortBy, -1);
            }
        }
    }

This dose not works with MongooseJS 3.3.1 . Query.sort(req.query.SortBy) gives sorted in ascending order.But not getting descending in any way. Please give a solution.

Problem courtesy of: dany

Solution

I wasn't able to recreate the problem you were experiencing. I would say to post the information about the collection you are querying along with the indexes you have on it.

I did rewrite your code to be easier to read:

var Query = Department.find(),
    sortBy = req.query.SortBy,
    sortType = (req.query.SortType || 'asc').toLowerCase();

if (sortBy && sortType === 'asc') {
    Query.sort(sortBy, 1);  
} else if (sortBy && sortType === 'desc') {
    Query.sort(sortBy, -1);
}

Update (2012-10-30)

I just realized that I had the incorrect syntax for the sort function. Please see corrected code.

var Query = Department.find(),
    sortBy = req.query.SortBy,
    sortType = (req.query.SortType || 'asc').toLowerCase();

if (sortBy && sortType === 'asc') {
    Query.sort(sortBy); // firstname
} else if (sortBy && sortType === 'desc') {
    Query.sort('-'+sortBy); // -firstname
}

See http://mongoosejs.com/docs/api.html#query_Query-sort for sort argument syntax.

Solution courtesy of: Julian Lannigan

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Sort in MongooseJS 3.3.1 in ascending and descending order

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×