Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJs: Mongodb query never called in cron job with node-cron

I have created a cron job to update some data in the database, but the query is never executed.

my cron job :

    const cron = require('node-cron');
    const Document = require('../models/document');
    const User = require('../models/user');
    const checkDocumentsDate = cron.schedule(
      '*/1 * * * *',
      async () => {
        console.log('here');
        Document.find().populate('user', (err, docs) => {
          console.log(err);
          if (!err) {
            docs.forEach((doc) => {
              console.log(doc);
            });
          }
        });
      },
      {
        scheduled: false,
      }
    );
    
    exports.startCheckDocumentsDate = () => {
      checkDocumentsDate.start();
    };

I call the startCheckDocumentsDate in app.js like :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    // CronJobs
    const { startCheckDocumentsDate } = require('./services/cron_tasks');
    // DB Connection
    mongoose
      .connect(process.env.DATABASE, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
      })
      .then(() => {
        console.log('DB CONNECTED');
        startCheckDocumentsDate();
      });

my console.log() :

DB CONNECTED
here  ===> console.log() inside cron job
here
here
here
here
here
here
here

Here is my document model , the user model is also look a like:

    const mongoose = require('mongoose');
    const mongoosePaginate = require('mongoose-paginate-v2');
    
    const { ObjectId } = mongoose.Schema;
    const documentSchema = new mongoose.Schema(
      {
        doctype: { type: String, required: true },
        url: {
          type: String,
        },
        filename: { type: String, required: true },
        fileid: { type: String, required: true, unique: true },
        verificationcount: {
          type: Number,
          default: 0,
        },
        verificationfailedcount: {
          type: Number,
          default: 0,
        },
        expiredate: Date,
        user: {
          type: ObjectId,
          ref: 'User',
          required: true,
        },
        idstabile: {
          type: ObjectId,
          ref: 'Stabile',
        },
        opinionby: [
          {
            type: ObjectId,
            ref: 'User',
          },
        ],
        opinionbyadditionalinfo: [
          {
            user: {
              type: ObjectId,
              ref: 'User',
            },
            approved: {
              type: Boolean,
            },
          },
        ],
      },
    
      { timestamps: true },
    );
    
    documentSchema.index({ user: 1, filename: 1 }, { unique: true });
    documentSchema.plugin(mongoosePaginate);
    
    module.exports = mongoose.model('Document', documentSchema);

Couldn’t find why it isn’t working. Probably there is something wrong with it.

Also moongose version is "mongoose": "^5.7.7"

>Solution :

Try to use .then instead of defining callback in .populate:

Document.find().populate('user').then((err, docs) => {

Since you are using async function, you can also refactor your code to use await syntax:

const checkDocumentsDate = cron.schedule('*/1 * * * *', async () => {
  try {
    console.log('here');
    let docs = await Document.find().populate('user');
    docs.forEach((doc) => { console.log(doc); });
  } catch(error) {
    console.log(err);
  }
},{
  scheduled: false,
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading