'Mongoose - how to access nested value by id

I'm trying to access the value of quantity of specific product by id.

Its works fine with getting amount but when trying to access quantity inside products array, cant get it.

As I see its about finding again the product by _id, then you can access it, i think.

This is how the model goes:

userId: { type: String, required: true },

products: [
      {
        productId: {
          type: String,
        },
        quantity: {
          type: Number,
          default: 1,
        },
      },
    ],

amount: { type: Number, required: true },

And this what im trying to do:

Notice that: "$amount" works fine but the problem is at (sales: productId && "$products.quantity") :

 $project: {
            month: { $month: "$createdAt" },
            sales: productId && "$products.quantity" || "$amount" ,
          },

Here full code:

getMonthIncome: async (req, res) => {
    const productId = req.query.pid;
    const date = new Date();
    const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
    const previousMonth = new Date(
      new Date().setMonth(lastMonth.getMonth() - 1)
    );
    try {
      const income = await Order.aggregate([
        {
          $match: {
            createdAt: { $gte: previousMonth },
            ...(productId && {
              products: { $elemMatch: { productId } },
            }),
          },
        },
        {
          $project: {
            month: { $month: "$createdAt" },
            sales: productId && "$products.quantity" || "$amount" ,  // <--- cant access quantity
          },
        },
        {
          $group: {
            _id: "$month",
            total: { $sum: "$sales" },
          },
        },
      ]);
      res.status(200).json(income);
    } catch (err) {
      res.status(500).json(err);
    }
  },
};


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source