javascriptnode.jsmongodbmongoosenode-cron

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 :

    // 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,
    });