【问题标题】:How to add Lazy loading in Node js?如何在 Node js 中添加延迟加载?
【发布时间】:2021-02-21 01:53:24
【问题描述】:
const posts = await Post.find().populate("receiver").populate("author")
        try {
            res.json({
                status: true,
                message: 'All posts fetched',
                data: posts.reverse()
            })

这是我将所有帖子发送到前端的代码。但我想在后端添加延迟加载。 后端不能一次性发送所有数据。在某个时间间隔后调用 1000 个提要帖子。 数据太大,无法通过api调用。

【问题讨论】:

  • 既然你使用的是populate我假设你使用的是猫鼬,尝试添加分页
  • Here你可以看到在mongoose中是如何使用skip和limit的

标签: javascript node.js mongodb lazy-loading


【解决方案1】:

我看到的第一件事:你为什么不把你的 await 放在 try / catch 块内?

您可以使用skiplimit

我喜欢这样做:

    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()
        })

根据您使用的是 GET 还是 POST,您需要向您的 API 发送额外的 page

在第 1 页,您将看到 10 个帖子。在跳过时,您有 10 乘以 1,即 10,但您不想在第一次获取时跳过 10 个帖子。因此,您需要减去 -1 以使 10 乘以 0 为 0,因此您在第一次获取时跳过 0。

【讨论】:

    猜你喜欢
    • 2017-11-28
    • 2012-04-07
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多