How to update a MongoDB collection automatically every midnight?

与世无争的帅哥 提交于 2021-02-05 06:55:06

问题


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 in all of the documents in a collection to false every midnight.

Can someone point me to the right direction on how to accomplish this?

I want to be able to scale it as well at some point - for example, have a value saved in a document in another collection to indicate the time where these boolean fields will be invalidated in the front end?

I'm using a MERN stack. Thanks for your help!


回答1:


you can use cron job

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

const updateCollections = async ()=>{
  await someQueriesServices()
}

new CronJob('0 0 * * *', async () => {
  await updateCollections()
}, null, true, 'America/Los_Angeles');

or you can use setInterval

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

setInterval(async ()=>{
    await updateCollections()
},Interval)



回答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!');
});


来源:https://stackoverflow.com/questions/58832157/how-to-update-a-mongodb-collection-automatically-every-midnight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!