🚀 Mongoose Aggregation Wrapper

Debug MongoDB aggregation pipelines stage by stage with TypeScript support

🎯 Why Use This Package?

MongoDB aggregation pipelines can be complex and hard to debug. This package helps you understand exactly what happens at each stage of your pipeline.

🔍

Debug Complex Pipelines

See exactly what each stage produces with detailed execution timing and sample results.

Optimize Performance

Identify slow stages and bottlenecks in your aggregation pipelines.

Validate Logic

Ensure each stage works as expected before moving to the next.

📚

Learn Aggregation

Understand how data flows through your pipeline step by step.

🔷

TypeScript Support

Full type safety and IntelliSense for better development experience.

🛠️

Zero Configuration

Works with your existing Mongoose models without any setup.

📦 Installation

Install via npm

npm install mongoose-aggregation-wrapper

Prerequisites: Node.js ≥ 14, Mongoose ≥ 7.0

7.0+
Mongoose Version
14+
Node.js Version
0kb
Runtime Dependencies
100%
TypeScript

🚀 Quick Start

Basic Usage

// ES6/TypeScript
import Wrapper from 'mongoose-aggregation-wrapper';

// CommonJS
const Wrapper = require('mongoose-aggregation-wrapper').default;

// Use with your existing Mongoose model
const results = await Wrapper(YourModel, pipeline);
                

Simple Example

import Wrapper from 'mongoose-aggregation-wrapper';

async function getUsersWithPosts(UserModel) {
  const pipeline = [
    { $match: { active: true } },
    { $sort: { createdAt: -1 } },
    { $limit: 10 },
    {
      $lookup: {
        from: 'posts',
        localField: '_id',
        foreignField: 'userId',
        as: 'posts'
      }
    }
  ];

  // This will execute each stage and show debug info
  const results = await Wrapper(UserModel, pipeline);
  return results;
}
                

📚 API Documentation

Function Signature

Wrapper<T = any>(
  model: mongoose.Model,           // Your Mongoose model
  pipeline: PipelineStage[],       // Array of aggregation stages
  options?: WrapperOptions         // Optional configuration
): Promise<T[]>
                

Options Interface

interface WrapperOptions {
  allowDiskUse?: boolean;    // MongoDB allowDiskUse option (default: false)
  debug?: boolean;           // Enable step-by-step execution (default: true)
  logResults?: boolean;      // Log sample results after each stage (default: true)
}
                

debug: boolean

Default: true

When true, executes pipeline stage by stage. When false, executes full pipeline at once.

logResults: boolean

Default: true

When true, shows sample documents after each stage execution.

allowDiskUse: boolean

Default: false

MongoDB option for handling large datasets that exceed memory limits.

🔧 Advanced Examples

E-commerce Product Aggregation

const pipeline = [
  // Stage 1: Filter active products
  { $match: { status: 'active', deleted: false } },
  
  // Stage 2: Sort by popularity
  { $sort: { popularity: -1, createdAt: -1 } },
  
  // Stage 3: Pagination
  { $skip: 0 },
  { $limit: 20 },
  
  // Stage 4: Lookup category details
  {
    $lookup: {
      from: 'categories',
      localField: 'categoryId',
      foreignField: '_id',
      as: 'category'
    }
  },
  
  // Stage 5: Calculate average rating
  {
    $addFields: {
      averageRating: { $avg: '$reviews.rating' },
      reviewCount: { $size: '$reviews' }
    }
  }
];

const products = await Wrapper(ProductModel, pipeline, {
  debug: true,
  logResults: true,
  allowDiskUse: true
});
                

Production Mode (No Debug)

// For production - execute full pipeline without debug info
const results = await Wrapper(Model, pipeline, {
  debug: process.env.NODE_ENV === 'development',
  logResults: process.env.NODE_ENV === 'development',
  allowDiskUse: true
});
                

☕ Support This Project

If this package helped you debug your aggregation pipelines and saved you time, consider buying me a coffee! Your support helps me maintain and improve this project.

💳 Buy me a coffee via PayPal Star on GitHub

💝 Other Ways to Support

  • Star the repository on GitHub
  • 🐛 Report bugs and suggest features
  • 📢 Share with your developer friends
  • 💻 Contribute code improvements
  • 📝 Write about it in your blog