DEV Community

NasreenKhalid
NasreenKhalid

Posted on • Updated on

Update Mongo DB By NodeJS Cron Job

We have multiple scenarios where we need to update our database fields at some particular time instants based on some conditions for example I need to update the status of all students to a particular batch after the course has finished, there are many ways to automate this process so that the fields in my database are updated automatically on a particular time.

Node JS Cron Package

Performing a particular task at a particular instant can be efficiently achieved through a Cron Job.
Node Cron is a handy npm package where you schedule different jobs and they run at the particular time instants periodically. Cron Jobs are common to achieve tasks like sending email notifications, deleting error logs or updating some order statuses etc.

Problem Statement

Today, I am also going to discuss a same scenario where I have a 'Campaigns' table in the mongo database and if the end_date of campaigns is lesser than today then I have to update the status of all those campaigns to 'inactive'. I will make use of Node JS Cron Job to run every midnight and check all the records in 'Campaigns' collection and update the ones that have the above mentioned condition.

Now let's start coding.
First we need to install node-cron package in our node app, I am assuming that you have already created a simple node/express app, if you are new to Node then you can follow my nodejs/express tutorial here.

Let's begin by installing node-cron package by using following command:

npm install --save node-cron
Enter fullscreen mode Exit fullscreen mode

Now in the index.js file we will import the cron package and schedule our job:

const cron = require('node-cron');
Enter fullscreen mode Exit fullscreen mode

Below is the cronjob runs every midnight and set the active campaigns to inactive if end_date is lesser than today

Also, note that first we need to convert today's date in the same format as saved in db

var todayDate = new Date().toISOString().substring(0, 10);

cron.schedule('0 1 * * *', () => {
  console.log('Running a task every midnight (1:00 am)');
  Campaign.findOneAndUpdate({ campaignStatus: 'active', end_date: { 

    $lt: todayDate, 

 }}, { $set:  {campaignStatus: 'inactive' }},

 {returnNewDocument: true}, (err, data) => {
  if (err) {
    return errorHandler(dbError, res);
  }
})
});
Enter fullscreen mode Exit fullscreen mode

The above job runs every midnight and update the campaigns status accordingly.

If you wish to read more about setting the time intervals in your cron jobs then this is a very helpful link describing all the asterisks purpose in our cron job schedule.

Hope you enjoyed reading this article and it helps you in your coding journey.

If you are looking for a learning experience that makes you a professional developer with hands-on coding skills, join one of the best courses here

Happy coding...

Top comments (0)