Home > other >  Progresively select sorted mongodb documents
Progresively select sorted mongodb documents

Time:05-19

Context:

My code is in JavaScript (mongoose)

I have a database with a lot of users, I want to create a leaderboard based on their scores. I plan to show 10 users at a time with arrows to navigate and show the next 10 users.

Ideas:

Is it possible to make a query and progressively get the users, like an iterator that fetches as I go?

Or have the limit:

await Users.find({})
        .sort({ score: -1 })
        .limit(10);

And rerun the query to get the next 10 users

Finally, I could just get the documents one at a time, but I don't really know how would I do this.

Any help would be greatly appreciated, thanks.

CodePudding user response:

you can use Skip and Limit for page navigation. i.e., pagination

const page = req.query.page * 1 || 1;
const limit = req.query.limit * 1 || 10;
const skip = (page - 1) * limit;

Then in the Query,

await User.find({})
          .sort({ score: -1 })
          .skip(skip).limit(limit);

Then in your Query

{{URL}}/User?page=1&limit=10
  • Related