0
const posts = await Post.find().populate("receiver").populate("author")
        try {
            res.json({
                status: true,
                message: 'All posts fetched',
                data: posts.reverse()
            })

This is my code that sending all posts to frontend. But I want add lazy loading on backend. Backend must not send all the data at one go.. calling 1000 feed posts after sometime interval. The data will be too large to call via api.

  • 2
    Since you are using `populate` I assume you are using mongoose, try adding pagination – Abishek Kumar Nov 09 '20 at 06:18
  • [Here](https://stackoverflow.com/questions/13935733/mongoose-limit-offset-and-count-query) you can see how skip and limit is used in mongoose – anttud Nov 09 '20 at 06:24

1 Answers1

1

First thing i see: Why didnt you put your await inside the try / catch block?

You can use skip and limit

I like to do it like this:

    let page = req.body.page - 1;
    let postAmount = 10;
    try {
        const posts = await Post.find().populate("receiver").populate("author").limit(postAmount).skip(postAmount * page)
        res.json({
            status: true,
            message: 'All posts fetched',
            data: posts.reverse()
        })

Depending on if you use GET or POST you will need to send additional page to your API.

On page 1 you will see 10 posts. At skip you have 10 multiply by 1 that is 10 but you dont want to skip 10 posts on your first fetch. So you need to subscract -1 to have 10 multiply by 0 is 0 so you skip 0 at your first fetch.

bill.gates
  • 14,145
  • 3
  • 19
  • 47