CRON NodeJs mongodb

故事扮演 提交于 2020-01-07 05:58:23

问题


  • Hello, I have a little problem, I want display every user's email from database Mongo in console.log();.
  • When I start my CRON I have result UNDEFINED.
  • Thanks for your answer

my code

var User = require('./models/user');

var CronJob = require('cron').CronJob;
var job = new CronJob('0-59 0-59 0-23 * * 0-6', function(req, res) {


    User.find(function(err, user) {
        console.log("CRON is started !" + user.email)
    });

}, function () {
    /* This function is executed when the job stops */
    console.log("CRON is stoped !")
},
true /* Start the job right now */
);

回答1:


I guess your are using Mongoose for the MongoDB related stuff and you defined your own User model. The result from MongoDb will be an array of objects so user.email is not possible. You have to iterate over all returned objects in the array.

Try using:

// get all the users
User.find({}, function(err, users) {

  // optional but i would recommend to use it so that you can see possible errors with your query
  if (err) throw err;

  // iterate over all users of all the users
  users.forEach(function(user) {
    console.log("CRON is started !" + user.email);
  });
});


来源:https://stackoverflow.com/questions/47780455/cron-nodejs-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!