In one project, the Android developer asked me to give me an API that can show product categories with the number of products in each category; the best way to create this API in MongoDB is to use the '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);
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); }); },
and this is postman result
Top comments (0)