'Sort items paginated - mongoose
I have a problem that I'm having a hard time solving. I have a list of users:
const users = [
{ name: "Noah" },
{ name: "Vladimir" },
{ name: "Nicolas" },
{ name: "Joe" },
{ name: "Timothy" },
{ name: "Nicole" },
{ name: "Mica" },
{ name: "Barack" },
{ name: "Ji Qin" },
{ name: "Patrick" },
]
These users must be paginated to be displayed in a table. To paginate these users I am using "aggregate", something like:
// User.Query, I am using GraphQL
function resolve(_, args) {
// Get arguments
const { skip, limit, sortBy } = args;
// Paginate users
const users = await Users.aggregate([
$facet: {
count: [{ $count: 'count' }],
users: [{ $skip: skip }, { $limit: limit }, { $sort: sortBy }],
},
$project: {
count: { $arrayElemAt: ["$count.count", 0] },
users: "$items",
},
])
/* This return something like
{
count: the total users
users: the users
}
*/
return users[0];
}
module.exports = resolve
Well the problem starts here: In the table I am showing two users per page, when I define a "limit", for example 2, it brings me two users per page, the problem is when ordering the users. When I sort the users by ascending name, it should bring me something like:
const users = [
{ name: "Barack" },
{ name: "Ji Qin" },
{ name: "Joe" },
{ name: "Mica" },
{ name: "Nicolas" },
{ name: "Nicole },
{ name: "Noah" },
{ name: "Patrick" },
{ name: "Timothy" },
{ name: "Vladimir" },
]
But it is ordering only the two elements that it brings me: on page 1, Noah and Vladimir return, on page 2, Joe and Nicolas return, on page 3, Nicole and Timothy return. Should return the users like the example above. How to solve this problem, thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
