【问题标题】:Automate NodeJS Express Get and Post request using Cron使用 Cron 自动化 NodeJS Express Get 和 Post 请求
【发布时间】:2021-10-05 14:39:53
【问题描述】:

我有一个来自数据库的现有获取和发布请求:

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.    
}

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

【问题讨论】:

    标签: node.js mongodb cron


    【解决方案1】:
    1. 没有来自cron 作业的响应,因为没有request 进入您的makeRequest 函数。这是有道理的,因为 cron 作业独立于任何传入请求。
    2. 另一个原因是,您可能无法从updateOne 操作中获取任何数据,因为它不会返回更新后的文档。它改为返回该操作的状态。看看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 调用并使用所需的参数/查询定义新路由。

    你的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" }
    );
    

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 1970-01-01
      • 2022-11-07
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 2019-06-26
      相关资源
      最近更新 更多