如何在每个午夜自动更新MongoDB集合



我目前有一个用MERN构建的SPA,我想通过在MongoDB数据库中的特定集合中添加计划更新来进一步改进它,方法是在每个午夜将集合中所有文档中的boolean字段设置为false。

有人能为我指出如何实现这一目标的正确方向吗?

我想在某个时候也能缩放它——例如,在另一个集合的文档中保存一个值,以指示这些boolean字段在前端无效的时间?

我使用的是MERN堆栈。谢谢你的帮助!

您可以使用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');

或者您可以使用setInterval

const timeInSec = moment().endOf('day').valueOf()
const Interval = Date.now() - timeInSec;
setInterval(async ()=>{
await updateCollections()
},Interval)

我通常使用节点调度

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

最新更新