如何在每个午夜自动更新MongoDB集合? [英] How to update a MongoDB collection automatically every midnight?
问题描述
我目前有一个使用MERN构建的SPA,我想通过在一个MongoDB数据库中的所有文档中设置一个 boolean
字段来向我的MongoDB数据库中的特定集合添加计划的更新来进一步改进它.每半夜收集一次虚假邮件.
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?
我希望能够在某个时候对其进行缩放-例如,在另一个集合中的文档中保存一个值,以指示这些 boolean
字段将在其中失效的时间.前端?
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?
我正在使用MERN堆栈.感谢您的帮助!
I'm using a MERN stack. Thanks for your help!
推荐答案
您可以使用 cron工作
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');
或者您可以使用 setInterval
const timeInSec = moment().endOf('day').valueOf()
const Interval = Date.now() - timeInSec;
setInterval(async ()=>{
await updateCollections()
},Interval)
这篇关于如何在每个午夜自动更新MongoDB集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!