简体   繁体   中英

How to add Lazy loading in Node js?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM