node.js - 如何在 Node js Express 服务器中每午夜更新日期变量以从新集合 `data-${date}` 中获取

标签 node.js firebase express google-cloud-firestore node-schedule

我有一个快速服务器,我需要从 firebase 获取新的甲酸盐集合 data-${date} 。如何使用 Node 调度(或任何其他方法)来完成此任务。

代码主要是格式


let date=new Date();

app.get("/fetch",(req,res) => {
        // fetch data from firestore db `data-${date}`
}

tldr:日期变量需要在每个午夜更新

最佳答案

您可以在 Node js Express 服务器中每午夜更新日期以从新集合中获取

const express = require("express");
const admin = require("firebase-admin");
const moment = require("moment");

const app = express();

admin.initializeApp({
  credential: admin.credential.cert("path/to/serviceAccountKey.json"), // 
  Replace with the path to your service account key file
});

const db = admin.firestore();

const baseCollectionName = "data";

let currentDate = moment().format("YYYY-MM-DD");

const fetchData = () => {
 const collectionName = `${baseCollectionName}-${currentDate}`;

 const collectionRef = db.collection(collectionName);

// Perform your desired operations on the collection here (e.g., fetching 
data)
 // ...
};

// Function to update the currentDate variable at midnight
const updateDateAtMidnight = () => {
 const nextMidnight = moment().endOf("day");
 const duration = moment.duration(nextMidnight.diff(moment()));

 const millisecondsUntilMidnight = duration.asMilliseconds();

 setTimeout(() => {
    currentDate = moment().format("YYYY-MM-DD");
    updateDateAtMidnight();
 }, millisecondsUntilMidnight);
};

updateDateAtMidnight();

app.get("/fetch", (req, res) => {
  fetchData();
});

app.listen(3000, () => {
 console.log("Server started on port 3000");
});

关于node.js - 如何在 Node js Express 服务器中每午夜更新日期变量以从新集合 `data-${date}` 中获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76382149/

相关文章:

node.js - 语法错误 : Invalid or Unexpected Token when running a nodejs file using Visual Studio Code (Using powershell)

node.js - 如何使用 Node.js Driver for DataStax graph 运行 OLAP 查询?

Firebase 电话验证 : some users don't receive OTP

javascript - 如何在生成 index.js 时修复 sequelize 连接问题?

node.js - 在 Express 的路由定义中指定子域

node.js - 将 AWS EC2 上托管的网站的 http 请求重定向到 https

javascript - 无法从 POST 请求检索 JSON 数据

android - 如何 “append” Firebase查询快照到流

java - 确认 Firebase Analytics 跟踪

jquery - Node.js Express - 如何动态提供模型数据?