如何按固定时间周期分批响应客户端请求的mongoose文档数据
Mongoose 固定时间周期分批返回文档实现方案
核心实现逻辑
- 将全量文档按固定大小(本需求为2条/组)拆分为多个批次
- 基于全局时间戳计算当前生效的批次索引,无需额外存储会话或全局状态,所有客户端同一时间请求拿到的批次完全一致
- 每个批次生效周期设置为5秒,周期结束后自动切换到下一批,所有批次遍历完成后自动从头循环
代码实现
小数据量方案(带缓存优化)
如果你的数据量不大,推荐用缓存全量文档的方案,减少数据库查询压力:
const YourModel = require('./models/yourModel'); // 替换为自身的Mongoose模型路径 // 固定配置参数 const BATCH_SIZE = 2; // 每批返回2条数据 const BATCH_DURATION = 5 * 1000; // 单批生效时长5秒 const CACHE_TTL = 60 * 1000; // 全量数据缓存有效期1分钟,可按需调整 let cachedDocs = []; let lastCacheUpdateTime = 0; // 接口处理逻辑 app.get('/fetch-batch-docs', async (req, res) => { try { const now = Date.now(); // 缓存过期或为空时重新拉取全量数据 if (!cachedDocs.length || now - lastCacheUpdateTime > CACHE_TTL) { // 按created_at排序保证批次顺序稳定,可按需调整排序规则 cachedDocs = await YourModel.find().sort({ created_at: 1 }).lean(); lastCacheUpdateTime = now; } const totalBatches = Math.ceil(cachedDocs.length / BATCH_SIZE); if (totalBatches === 0) return res.json([]); // 计算当前生效的批次索引 const currentBatchIndex = Math.floor(now / BATCH_DURATION) % totalBatches; // 切片获取对应批次数据 const result = cachedDocs.slice(currentBatchIndex * BATCH_SIZE, (currentBatchIndex + 1) * BATCH_SIZE); return res.json(result); } catch (err) { console.error('数据查询失败:', err); return res.status(500).json({ error: '服务端内部错误' }); } });
大数据量方案
如果数据量过大不适合全量缓存,可以直接通过skip+limit查询对应批次:
const YourModel = require('./models/yourModel'); const BATCH_SIZE = 2; const BATCH_DURATION = 5 * 1000; app.get('/fetch-batch-docs', async (req, res) => { try { const now = Date.now(); const totalCount = await YourModel.countDocuments(); const totalBatches = Math.ceil(totalCount / BATCH_SIZE); if (totalBatches === 0) return res.json([]); const currentBatchIndex = Math.floor(now / BATCH_DURATION) % totalBatches; const result = await YourModel.find() .sort({ created_at: 1 }) .skip(currentBatchIndex * BATCH_SIZE) .limit(BATCH_SIZE) .lean(); return res.json(result); } catch (err) { console.error('数据查询失败:', err); return res.status(500).json({ error: '服务端内部错误' }); } });
注意事项
如果需要调整批次大小、生效周期、排序规则,直接修改对应配置参数即可,时间计算逻辑无需改动。如果数据更新频率高,可以缩短缓存有效期,或者在数据更新时主动清空
cachedDocs保证返回最新数据。
内容的提问来源于stack exchange,提问作者Fırat Doğan
相关产品推荐
相关产品推荐

