2

I have a MongoDB database and a React web page that shows the content using http requests to my Node.js server. This Node.js uses mongoose to communicate with the DB. The react web page shows up to 10 entries per page and it is slow when the database gets big:

React web page

What Node.js is doing:

router.get("/", async (req, res) => {
    const movies = await Movie.find()
        .select("-__v")
        .sort("name");
    res.send(movies);
});

As you can see, Node.js returns all the database and the front end React only displays the 10 entries depending on the page the user is viewing.

It would be optimal to fetch from the database only 10 entries depending on the page the user is looking at.

How can I do that?

Thanks

Goto
  • 43
  • 4

3 Answers3

2

You can use skip() and limit() to do this.

Example:

const movies = await Movie.find()
    .select("-__v")
    .skip(perPage * currentPage)
    .limit(perPage)
    .sort("name");

Or you can use pagination package like mongoose-paginate...

Cuong Le Ngoc
  • 11,595
  • 2
  • 17
  • 39
0

Yes there is skip and limit methods to get certain amount of data fron db.

router.get("/", async (req, res) => {
    const movies = await Movie.find()
    .select("-__v").skip(10).limit(10)  // use skip and limit value as you want. 
    .sort("name");
    res.send(movies);
});
Nasir Kamal
  • 114
  • 1
  • 7
0

You can limit the number of returned objects with .limit(n).

router.get("/", async (req, res) => {
    const movies = await Movie.find()
        .select("-__v")
        .sort("name")
        .limit(10);
    res.send(movies);
});

There has been a post already with this question. Refer to this question.

Abhishek Kasireddy
  • 371
  • 1
  • 4
  • 16