如何在Node.js Express服务器每日凌晨更新日期变量获取Firebase指定集合
每日更新Firebase集合名称的实现方案
方案一:请求时实时计算日期(推荐)
无需依赖定时任务,每次收到/fetch请求时直接计算当天日期,生成对应集合名称,确保永远获取当日的目标集合,避免定时任务失效的风险。
代码示例:
app.get("/fetch", (req, res) => { // 按需求格式化日期(示例为YYYY-MM-DD,可根据集合命名规则调整) const today = new Date(); const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`; // 从Firebase获取对应集合 const targetCollection = db.collection(`data-${dateStr}`); // 执行查询并返回结果 targetCollection.get() .then(querySnapshot => { const result = []; querySnapshot.forEach(doc => result.push(doc.data())); res.json(result); }) .catch(err => res.status(500).json({ error: err.message })); });
方案二:使用node-schedule定时更新全局日期变量
如果需要通过定时任务维护全局日期变量,可按以下步骤实现:
- 先安装依赖:
npm install node-schedule
- 代码实现:
const schedule = require('node-schedule'); let currentDateStr; // 定义日期更新函数 function refreshDate() { const today = new Date(); currentDateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`; } // 服务器启动时初始化日期 refreshDate(); // 每日凌晨0点执行日期更新 schedule.scheduleJob('0 0 * * *', () => { refreshDate(); console.log('日期变量已更新为:', currentDateStr); }); app.get("/fetch", (req, res) => { // 使用全局日期变量获取目标集合 const targetCollection = db.collection(`data-${currentDateStr}`); // 执行查询并返回结果 targetCollection.get() .then(querySnapshot => { const result = []; querySnapshot.forEach(doc => result.push(doc.data())); res.json(result); }) .catch(err => res.status(500).json({ error: err.message })); });
注意:0 0 * * *是Cron表达式,代表每日凌晨0点触发任务。若服务器重启,需确保启动时先执行一次refreshDate初始化日期。
内容的提问来源于stack exchange,提问作者Harsh Singh
相关产品推荐
相关产品推荐

