【发布时间】:2020-10-04 20:09:07
【问题描述】:
我知道有多个帖子处理类似类型的问题,但似乎没有一个适合我。
在我的应用程序中,我需要从我的数据库中获取垂直条形图的图形数据。过滤基于两种状态类型和 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)
感谢您帮助解决问题:)
【问题讨论】:
-
Cannot set headers after they are sent to the client表示您多次发送请求响应!检查你的代码。 -
@AnaLava 在我的第二种方法中,我只发送一个 res.json()
-
在您的发送方法中,如果
fetchMonths有多个条目,这意味着res.status(200).json(...也被多次调用(在map函数的每次迭代中)如上所述 -
@Vishnu 第一种方法怎么样?你能帮我理解未决承诺的原因吗?
标签: node.js mongoose highcharts aggregate