未处理的承诺拒绝猫鼬聚合

时间:2020-06-15 12:00:58

标签: node.js mongoose highcharts aggregate

我知道有多个帖子处理类似的问题,但是似乎没有一个适合我。

在我的应用程序中,我需要从数据库中获取垂直条形图的图形数据。过滤基于两种状态类型和updatedAt字段。将会绘制一年中每个月的数据。

我尝试了两种方法来实现同一目的:

第一

exports.leads_based_on_status = async (req, res) => {
  const { userId } = req.user;
  const fetchMonths = getMonths();

  try {
    const fetch_leads_new = await fetchMonths.map(async (month) => {
      return Lead.aggregate([
        {
          $match: {
            userId: mongoose.Types.ObjectId(userId),
          },
        },
        {
          $unwind: "$leads",
        },
        {
          $match: {
            $and: [
              { updatedAt: { $gt: month._start, $lt: month._end } },
              { "leads.status": "New" },
            ],
          },
        },
      ]);
    });

    const fetch_leads_pending = await fetchMonths.map(async (month) => {
      return Lead.aggregate([
        {
          $match: {
            userId: mongoose.Types.ObjectId(userId),
          },
        },
        {
          $unwind: "$leads",
        },
        {
          $match: {
            $and: [
              { updatedAt: { $gt: month._start, $lt: month._end } },
              { "leads.status": "Pending" },
            ],
          },
        },
      ]);
    });

    Promise.all([fetch_leads_new, fetch_leads_pending]).then(
      (resultnew, resultpending) => {
        console.log("show result new", resultnew);

        console.log("show result pending", resultpending);

        //both these results in Promise <pending>
      }
    );

    const leads_status_statics = [
      {
        New: fetch_leads_new,
      },
      {
        Pending: fetch_leads_pending,
      },
    ];
    res.status(200).json({ message: "Graphical Data", leads_status_statics });
  } catch (error) {
    console.log(error) || res.status(500).json({ error });
  }
};

第二:

exports.leads_based_on_status = async (req, res) => {
  const { userId } = req.user;
  const fetchMonths = getMonths();

  try {
    fetchMonths.map(async (month) => {
      const fetch_leads_new = await Lead.aggregate([
        {
          $match: {
            userId: mongoose.Types.ObjectId(userId),
          },
        },
        {
          $unwind: "$leads",
        },
        {
          $match: {
            $and: [
              { updatedAt: { $gt: month._start, $lt: month._end } },
              { "leads.status": "New" },
            ],
          },
        },
      ]);

      const fetch_leads_pending = await Lead.aggregate([
        {
          $match: {
            userId: mongoose.Types.ObjectId(userId),
          },
        },
        {
          $unwind: "$leads",
        },
        {
          $match: {
            $and: [
              { updatedAt: { $gt: month._start, $lt: month._end } },
              { "leads.status": "New" },
            ],
          },
        },
      ]);

      const leads_status_statics = [
        {
          New: fetch_leads_new,
        },
        {
          Pending: fetch_leads_pending,
        },
      ];
      res.status(200).json({ message: "Graphical Data", leads_status_statics });

      //de:16484) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    });
  } catch (error) {
    console.log(error) || res.status(500).json({ error });
  }
};

但是他们都无法帮助我解决问题。第一种方法不断返回Promise <Pending>,而第二种方法返回Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:467:11)

任何帮助纠正该问题的方法都值得赞赏:)

1 个答案:

答案 0 :(得分:1)

关于您的第一方法,Promise.all(iterable)方法以可迭代方式作为输入。就您而言,fetch_leads_newfetch_leads_pending已经返回了一个待处理的Promise数组,例如 :[ Promise { <pending> }, Promise { <pending> } ]

因此,当前您正在将具有数组或未完成的promise(Promise.all([fetch_leads_new, fetch_leads_pending]))的数组传递给Promise.all函数,例如

Promise.all([[ Promise { <pending> }, Promise { <pending> } ], [ Promise { <pending> }, Promise { <pending> } ]])

所以我认为您可以考虑使用两种Promise.all方法,其中一种等待fetch_leads_new,另一种等待fetch_leads_pending

const newRecords = await Promise.all(fetch_leads_new);
const pendingRecords = await Promise.all(fetch_leads_pending);

const leads_status_statics = [
  {
    New: newRecords,
  },
  {
    Pending: pendingRecords,
  },
];

关于第二方法

fetchMonths有多个条目时,意味着res.status(200).json(...也被多次调用(在map函数的每次迭代中),以及为什么会出现Cannot set headers after they are sent to the client错误