首页 > 解决方案 > 如何使用 Mongoose 和 MongoDB 进行分页

问题描述

我一直在阅读说不要使用 skip() 和 limit() 的帖子,因为如果 MongoDB 中有超过 1000 个条目,它就不会扩展。

所以,我实际上是这个 MERN 的新手,我正在尝试实现分页,但我什至不知道如何正确地做到这一点。这是我的问题:

router.get('/male', async (req, res) => {
  const current_id = await Posts.find({}).sort({ _id: -1 }).limit(1);
  // const current_id;
  const N = '/api/posts/male';
  const page_size = 15;
  try {
    const posts = await Post.find({ _id: { $lt: current_id } }).sort({ date: -1 }).skip((N - 1) * page_size).limit(page_size).
      res.json(posts);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

我从这个MongoDB 范围分页中得到了这个例子,现在我只是想在我的身上实现它。链接声明 const current_id 没有值,所以我假设您需要传递最后插入的 id,这是发出第一个请求的原因。常量 N 和 page_size 也是如此(我必须给它们一个值)。

对此感到抱歉,但我确实是新手, find() 中的 $lt 是什么意思?

现在它只是在 Devtools 控制台中显示 500 错误。

谢谢!

标签: node.jsmongoosereact-hooksmern

解决方案


推荐阅读