简体   繁体   English

在NodeJS cronjob中未调用猫鼬查询回调

[英]Mongoose query callback not invoked in NodeJS cronjob

I'm building a REST API backend in NodeJS, and testing it out locally. 我正在NodeJS中构建一个REST API后端,并在本地对其进行测试。 I'm trying to run a cron job that clears expired 'login token reset codes', codes temporarily created for resetting passwords, from the database. 我正在尝试执行cron作业,以从数据库中清除过期的“登录令牌重置代码”,即为重置密码而临时创建的代码。 I'm essentially performing a Mongoose query, and re-saving some of that data. 我实质上是在执行Mongoose查询,然后重新保存一些数据。

I use the following steps to create a cron job on Mac OSX: 我使用以下步骤在Mac OSX上创建cron作业:

  • 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. 该作业在crontab -l列出,它应该每分钟执行一次。

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. 使用输出到日志文件的console.log ,我可以确认 cronjob正在运行并且已读取文件。

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. 在日志文件中,我收到'clearLoginTokenResetCodes()'但未收到'clearLoginTokenResetCodes()' 'Searched' -特别是,我的Mongoose find()查询从未完成。 I can confirm this works, by calling it on the normal Node server. 我可以通过在普通的Node服务器上调用它来确认它是否有效。

It is possible that the cronjob finishes before Mongo finishes searching. cronjob可能在Mongo完成搜索之前完成。 What could be the problem behind this, and hence the 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. 猫鼬将使数据库交互排队,直到建立初始连接为止,但是您忘记了实际连接到数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM