Ihtisham Tanveer
Ihtisham Tanveer

Reputation: 388

mongoDB sorting not working with skip and limit

i am using query to find products from mongoDB collection. i am using different query filters with skip() and limit() everything is working great whenever i use sort with that it is not sorting the records "asc" and "desc" order.

here is my code

Products.find(filter)
        .sort({ column: order })
        .skip(parseInt(pageNumber, 10) * parseInt(nPerPage, 10))
        .limit(parseInt(nPerPage, 10));

Upvotes: 0

Views: 1146

Answers (2)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

Your code will sort the results based on the column named "column", you need to provide the dynamic property.

Below is 1 way to create a sort object with the dynamic property then use it in the query.

let sort = {};
sort[column] = order;

Products.find(filter)
        .sort(sort)
        .skip(parseInt(pageNumber, 10) * parseInt(nPerPage, 10))
        .limit(parseInt(nPerPage, 10));

You can try this way too:

Products.find(filter)
        .sort({[column]: order })
        .skip(parseInt(pageNumber, 10) * parseInt(nPerPage, 10))
        .limit(parseInt(nPerPage, 10));

Upvotes: 1

Raj
Raj

Reputation: 116

Did you use { column_name: 1, -1 } like .sort({ name: 1})?

Upvotes: 0

Related Questions