Question

I'm building a REST API backend in NodeJS, and testing it out locally. I'm trying to run a cron job that clears expired 'login token reset codes', codes temporarily created for resetting passwords, from the database. I'm essentially performing a Mongoose query, and re-saving some of that data.

I use the following steps to create a cron job on Mac OSX:

  • crontab -e
  • i
  • * * * * /usr/local/bin/node PATH_TO_NODE_FILE > PATH_TO_OUTPUT_FILE
  • Esc
  • ZZ

The job is listed in crontab -l, it should be executing every minute.

The script is pretty simply:

require('./../helpers/global.js')(); //  Setup Global 
var User = require('./../models/user.js'); // Import User Model

User.clearLoginTokenResetCodes(); // Call function to perform database query and modification

And using a console.log, which outputs to the log file, I can confirm that the cronjob is running and the file is read.

However, in the function block in the user model file:

userSchema.statics.clearLoginTokenResetCodes = function() {
  console.log('clearLoginTokenResetCodes()');
  var self = this;
  self.find({'loginTokenResetCode.expiryDate': {$lt: (new Date())}}).exec(function(err, users) {
    console.log('Searched');
  });
};

In the log file, I receive 'clearLoginTokenResetCodes()' but not 'Searched' - particularly, my Mongoose find() query is never completed. I can confirm this works, by calling it on the normal Node server.

It is possible that the cronjob finishes before Mongo finishes searching. What could be the problem behind this, and hence the solution?

Was it helpful?

Solution

My guess is your code is never actually connecting to the database. Mongoose will queue up DB interactions until the initial connection is made, but you have forgotten to actually connect to the database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top