mongodb “消息”:“无法读取未定义的属性(阅读'affiliateStats')”

qcbq4gxm  于 2023-01-04  发布在  Go
关注(0)|答案(1)|浏览(122)

当我尝试运行此代码时,它在我的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 });
  }
};

'

ulydmbyx

ulydmbyx1#

可能有两个原因:

  1. match语句有问题,返回的数据为空
    1.查找返回空数组,而展开没有preserveNullAndEmptyArrays: <boolean>,这将生成空结果

相关问题