DEV Community

loading...
Cover image for get number of product in each category with mongodb aggregate

get number of product in each category with mongodb aggregate

ma2web
MERN Stack Developer
・1 min read

In one project the Android developer ask to me to give me a api which can show product categories with number of product in each category, the best way to create this api in mongodb is aggregate operator,
this was my category schema:

const mongoose = require("mongoose");
const { s, rs, n, ref } = require("../utils/mongo");

var schema = new mongoose.Schema(
  {
    user: ref("user"),
    name: { ...rs, unique: true },
    description: s,
    image: s,
    view: {
      ...n,
      default: 0,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("category", schema);
Enter fullscreen mode Exit fullscreen mode

and you can see my controller in below

module.exports = {
  getAll: async (req, res) => {
    await Category.aggregate([
        {
          $lookup: {
            from: "products",
            localField: "_id",
            foreignField: "categories",
            as: "products",
          },
        },
        {
          $project: {
            _id: 1,
            name: 1,
            products: { $size: "$products" },
            description: 1,
            view: 1,
            createdAt: 1,
            updatedAt: 1,
          },
        },
      ]).exec(function (err, result) {
        if (err) throw err;
        res.send(result);
      });
  },
Enter fullscreen mode Exit fullscreen mode

and this is postman result

postman result

Discussion (0)