Skip to content Skip to sidebar Skip to footer

How To Update A Mongodb Collection Automatically Every Midnight?

I currently have an SPA built with MERN and I want to improve it further by adding a scheduled update to a particular collection in my MongoDB database by setting a boolean field i

Solution 1:

you can use cron job

const moment = require('moment');
constCronJob = require('cron').CronJob;

const updateCollections = async ()=>{
  awaitsomeQueriesServices()
}

newCronJob('0 0 * * *', async () => {
  awaitupdateCollections()
}, null, true, 'America/Los_Angeles');

or you can use setInterval

const timeInSec = moment().endOf('day').valueOf()
constInterval = Date.now() - timeInSec;

setInterval(async ()=>{
    awaitupdateCollections()
},Interval)

Solution 2:

I usually use node-schedule

const schedule = require('node-schedule');

const j = schedule.scheduleJob('42 * * * *', function(){
  console.log('The answer to life, the universe, and everything!');
});

Post a Comment for "How To Update A Mongodb Collection Automatically Every Midnight?"