0

I have two collections named graphData and users. 'users' collection has documents that store the user information. 'graphData' has 10 documents initially that has some dummy data regarding the number of users in the last 10 days. Now, I want a query to fire automatically after 24 hours that finds the number of users at that time and adds it to graphData and deletes one document also (using TTL index, I figured that out)

Please tell if there is some way to do this. Thanks I am using MERN stack (MongoDB, Express, ReactJS and NodeJS)

2 Answers2

2

To add onto the excellent answer from @Ifaruki, you can use a module like node-cron, this will ensure that you code is not dependent on the OS or cloud platform you are running. And scheduling something to run on a specific time is as simple as:

var cron = require('node-cron');

cron.schedule('* * * * *', () => {
  console.log('running a task every minute');
});

However do note that this will need to have your node+express app running all the time, which I assume you are running based on the stack you have mentioned.

P.S. If you plan to run it the app all the time, do take a look at forever or pm2 node modules.

If this is not the case stick to the accepted answer.

Yogesh_D
  • 17,656
  • 10
  • 41
  • 55
1

You could use linux cron jobs to execute an specific file every 24 hours.

You need to connect with SSH to your server, lets say putty, then type in

crontab -e

Then add following

5 0 * * * /usr/local/bin/node /home/somepath/example/script.js

This crontab means, execute this script every 5 mins after midnight.

For testing you can go with

* * * * * /usr/local/bin/node /home/somepath/example/script.js

This cron job means: Execute this script at every min, with it you can first test if you did everything right to see if it works

If you are using heroku you might read this question: Using Heroku Scheduler with Node.js

bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • what if i have deployed my web app to heroku. i can't use this method right? – Sukrit Kapil Jun 09 '20 at 06:31
  • 1
    i never have used heroku i have my own VPS so i dont know. You might read the heroku scheduler how to solve it. this could help you https://stackoverflow.com/questions/13345664/using-heroku-scheduler-with-node-js – bill.gates Jun 09 '20 at 06:34
  • 1
    @SukritKapil i will add it to my answer – bill.gates Jun 09 '20 at 06:38