skip to Main Content

when i try to run this code it give me the error on my console.log

"message":"Cannot read properties of undefined (reading ‘affiliateStats’)"

why does it happen?how can i make it work?
im new in ReactJs
Here’s my code:

`

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 });
  }
};

`

2

Answers


  1. There may be two causes:

    1. problem with match statement, the returning data is empty
    2. lookup is returning empty array and unwind does not have preserveNullAndEmptyArrays: <boolean> which yields to empty result
    Login or Signup to reply.
  2. I am following the same tutorial. I did some research and found that it cannot map on undefined values and I believe the one in question is affiliateSales. To fix it I initialized const { affiliateSales } = []; underneath const { id } = req.params;. Hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search