Sunday, 26 December 2021

Mongoose query - groupBy category and get last 4 items of each category

I am struggling in Writing that fetches 4 Products of each category. What I have done is

 exports.recentproducts = catchAsync(async (req, res, next) => {
     const doc = await Product.aggregate([
    { $sort: { date: -1 } },
    {
      $replaceRoot: {
        newRoot: {
          $mergeObjects: [{ $arrayElemAt: ['$products', 0] }, '$$ROOT'],
        },
      },
    },
    {
      $group: {    
        _id: '$productCategory',
        products: { $push: '$$ROOT' },
      },
    },

    {
      $project: {
        // pagination for products
        products: {
          $slice: ['$products', 4],
        },
        _id: 1,
       
      },
    },
    {
       $lookup: {
           from: 'Shop',
           localField: 'shopId',
           foreignField: '_id',
           as: 'shop',
     },
    },
  ]);

Document Model

const mongoose = require('mongoose');
   var ProductSchema = mongoose.Schema({
    title: {
        type: String,
        require: [true, 'Product must have a Title!'],
      },
      productCategory: {
        type: String,
        require: [true, 'Product must have a Category!'],
      },
      shopId: {
        type: mongoose.Schema.ObjectId,
        ref: 'Shop',
        require: [true, 'Product must have a Shop!'],
      },
    });
    
    var Product = mongoose.model('Product', ProductSchema);
    module.exports = Product;

expected result---

result= [
    {
        productCategory: "Graphics",
        products:[//4 products object here
           {
               must populate shop data
           }
       ]
    },
    {
        productCategory: "3d",
        products:[//4 products object here]
    },
       //there are seven categories I have like that
  ]
     

The Code i have done is working fine but it has two problems It does not populate shopId from Shop Model even through I have tried lookup It does not sort products in descending order(does not sort by date)



from Mongoose query - groupBy category and get last 4 items of each category

No comments:

Post a Comment