skip to Main Content

I have an express server server where I need to fetch new collection from firebase that is of formate data-${date} . How can I use node schedule (or anyother method) to accomplish this task .

Code is mainly of format


let date=new Date();

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

tldr: date variable needs to be updated every midnight

2

Answers


  1. node scheduler like many other schedulers are based on cronJobs.

    So you need to define a cronSettings

    const cronSettings = '0 0 * * *'
    // attach your function to the scheduler
    
    const scheduledJob = schedule.scheduleJob(cronSettings , functionToUpdate)
    
    

    You seem to use an express endpoint this is ok if you want also to trigger manually .

    const functionToUpdate = (req, res){
       // doing something
    }
    
    
    app.get("/fetch",functionToUpdate)
    

    hope it helps

    Balint

    Login or Signup to reply.
  2. You can update date every midnight in node js express server to fetch from new collection

    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");
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search