我有一个快速服务器,我需要从 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/