Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

NasreenKhalid
NasreenKhalid

Posted on • Edited 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 tutorialhere.

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

npm install --save node-cron
Enter fullscreen modeExit 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 modeExit 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 modeExit 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 helpfullink 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 courseshere

Happy coding...

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

An aspiring web developer, learner who believes in constant learning and grooming...
  • Location
    KSA
  • Work
    Web developer
  • Joined

More fromNasreenKhalid

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp