Raghav Herugu
Raghav Herugu

Reputation: 546

Mongoose and Express JS, find documents in a range

I have a Mongo DB database with 80 or so documents. I want to only display documents from the 12th document to the 24th, or the 3rd to the 50th, etc.

What I mean by this, is since I have 80 documents, I only want to display a certain range of documents. For example, the number 12th document in the database all the way to the 24th.

How would I do this efficiently?

Thanks

Upvotes: 2

Views: 214

Answers (1)

Owl
Owl

Reputation: 6853

you can use skip and limit

const perPage = 12;

let page = 0;
// Select the 1st - 12th document
await this.SomeModel
    .find(query)
    .skip(page*perPage)
    .limit(perPage);

page = 1;
// Select the 13th - 24th document
await this.SomeModel
    .find(query)
    .skip(page*perPage)
    .limit(perPage);

Upvotes: 1

Related Questions