当我尝试运行此代码时,它在我的console.log上给我错误
"消息":"无法读取未定义的属性(正在读取'affiliateStats')"
为什么会发生这种情况?我怎么才能让它工作?我在ReactJs新这里是我的代码:
'
import mongoose from "mongoose";
import User from "../models/User.js";
import Transaction from "../models/Transaction.js";
export const getAdmins = async (req, res) => {
try {
const admins = await User.find({ role: "admin" }).select("-password");
res.status(200).json(admins);
} catch (error) {
res.status(404).json({ message: error.message });
}
};
export const getUserPerformance = async (req, res) => {
try {
const { id } = req.params;
const userWithStats = await User.aggregate([
{ $match: { _id: new mongoose.Types.ObjectId(id) } },
{
$lookup: {
from: "affiliatestats",
localField: "_id",
foreignField: "userId",
as: "affiliateStats",
},
},
{ $unwind: "$affiliateStats" },
]);
const saleTransactions = await Promise.all(
userWithStats[0].affiliateStats.affiliateSales.map((id) => {
return Transaction.findById(id);
})
);
const filteredSaleTransactions = saleTransactions.filter(
(transaction) => transaction !== null
);
res
.status(200)
.json({ user: userWithStats[0], sales: filteredSaleTransactions });
} catch (error) {
res.status(404).json({ message: error.message });
}
};
'
1条答案
按热度按时间ulydmbyx1#
可能有两个原因:
1.查找返回空数组,而展开没有
preserveNullAndEmptyArrays: <boolean>
,这将生成空结果