node.js - 如何使用 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 错误。
谢谢!
解决方案
推荐阅读
- android - manager.queryUsageStats 在服务中返回一个空列表
- python - 如何在 default_get 函数中获取父值?在 Odoo 9
- tensorflow - 张量流 - 音频识别流的准确性
- .net - TS2474 (TS) 在“const”枚举声明中,成员初始化器必须是常量表达式
- openlayers - Openlayers 4.6上的多个标记具有不同的图标?
- rest - 在 Service Now 中发布附件
- python-3.x - 使用可变链接在浏览器中打开选项卡
- python-3.x - 二和python解决方案
- c++ - 在 C++ 代码中使用项目属性/宏
- python - pandas 计算子组的比例