使用 Cron 自动化 NodeJS Express Get 和 Post 请求

Automate NodeJS Express Get and Post request using Cron

我有一个现有的 get 和 post 来自数据库的请求是:

router.post('/stackExample', async (req, res) => {
  try {

    //MAKE GET REQUEST FROM MONGODB
    const stackCron = await Borrower.aggregate([
      { $unwind: { path: "$application", preserveNullAndEmptyArrays: true } },
      {
        $project: {
          'branch': '$branch',
          'status': '$application.status',
        },
      },
      { $match: { status: 'Active' } },
    ]);      

//MAKE POST REQUEST TO MONGODB
    for (let k = 0; k < stackCron.length; k++) {
      const branch = stackCron[k].branch;
      const status = stackCron[k].status;    
      const lrInterest = await Financial.updateOne({ accountName: 'Processing Fee Income'},
        {
          $push:
          {
            "transactions":
            {
              type: 'Credit',
              firstName: 'SysGen',
              lastName: 'SysGen2',
              amount: 100,
              date: new Date(),
            }
          }
        })
    }    

    res.json({ success: true, message: "Success" });
     } catch (err) { res.json({ success: false, message: 'An error occured' }); }

  });

如果使用客户端发出请求,此代码工作正常,但我想通过 cron 自动执行此操作:

这是我所做的:

var CronJob = require('cron').CronJob;
var job = new CronJob('* * * * * *', function () {

  makeRequest()

}, null, true, 'America/Los_Angeles');
job.start();



function makeRequest(message){
//Copy-paste entire router post request.    
}

如果我将我的代码复制粘贴到函数中,似乎没有任何反应。我错过了什么?

  1. cron 作业没有响应,因为没有 request 进入您的 makeRequest 函数。这是有道理的,因为 cron 作业独立于任何传入请求。
  2. 您可能无法从 updateOne 操作中获取任何数据的另一个原因是它没有 return 更新的文档。它 return 是该操作的状态。看看here。如果您想获取更新的文档,您可能需要使用 findOneAndUpdate.
const response = await Todo.findOneAndUpdate(
  { _id: "a1s2d3f4f4d3s2a1s2d3f4" },
  { title: "Get Groceries" },
  { new: true }
);
// response will have updated document
// We won't need this here. This is just to tell you how to get the updated document without making another database query explicitly
  1. 您的路由器函数的主体正在执行 async/await 操作。但是您没有将 makeRequest 函数指定为 async。这也可能是问题。
  2. cron 作业将更新数据库,但如果您想获取更新的文档,则必须对服务器进行 GET 调用并定义一个新路由,需要 parameters/query.

你的 makeRequest 函数看起来像这样

async function makeRequest() {
  try {
    //MAKE GET REQUEST FROM MONGODB
    const stackCron = await Borrower.aggregate([
      { $unwind: { path: "$application", preserveNullAndEmptyArrays: true } },
      {
        $project: {
          branch: "$branch",
          status: "$application.status",
        },
      },
      { $match: { status: "Active" } },
    ]);

    //MAKE POST REQUEST TO MONGODB
    for (let k = 0; k < stackCron.length; k++) {
      const branch = stackCron[k].branch;
      const status = stackCron[k].status;
      const lrInterest = await Financial.updateOne(
        { accountName: "Processing Fee Income" },
        {
          $push: {
            transactions: {
              type: "Credit",
              firstName: "SysGen",
              lastName: "SysGen2",
              amount: 100,
              date: new Date(),
            },
          },
        }
      );
    }
    /**
     * Write to a log file if you want to keep the record of this operation
     */
  } catch (err) {
    /**
     * Similarly write the error to the same log file as well.
     */
  }
}

在你的 cron 工作中

var job = new CronJob(
  "* * * * * *",
  async function () {
    await makeRequest();
  },
  null,
  true,
  "America/Los_Angeles"
);


你的新路线

router.get("/stack/:accountName", async (req, res, next) => {
  const { accountName } = req.params;
  try {
    const financial = await Financial.find({ accountName });
    res.status(200).json({ message: "success", data: financial });
  } catch (err) {
    res.status(500).json({ message: "error", reason: err.message });
  }
});

就这么叫吧

fetch(
  `http://example.net/stack/${encodeURIComponent("Processing Fee Income")}`,
  { method: "GET" }
);