Reputation: 1871
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.
Upvotes: 0
Views: 1745
Reputation: 6522
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.
Upvotes: 1
Reputation: 10780
The documentation explains it here: http://mongoosejs.com/docs/api.html#query_Query-sort
Upvotes: 0