mongoose-aggregation-wrapper
Version:
š TypeScript wrapper for debugging MongoDB/Mongoose aggregation pipelines stage-by-stage. Debug complex aggregations, optimize performance, and understand data flow with detailed execution timing and sample results.
61 lines (60 loc) ⢠2.65 kB
JavaScript
;
/**
* Mongoose Aggregation Pipeline Debugger Wrapper
* Executes each stage of an aggregation pipeline step by step and logs results
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Wrapper = Wrapper;
async function Wrapper(model, pipeline, options = {}) {
if (!model || typeof model.aggregate !== 'function') {
throw new TypeError('model must be a Mongoose model with an aggregate method');
}
if (!Array.isArray(pipeline)) {
throw new TypeError('pipeline must be an array of aggregation stages');
}
const { debug = true, logResults = true, allowDiskUse = false } = options;
if (!debug) {
// If debug is false, run the full pipeline at once
return model.aggregate(pipeline).option({ allowDiskUse }).exec();
}
console.log('š Starting Aggregation Pipeline Debug Mode');
console.log(`š Total stages: ${pipeline.length}`);
console.log('='.repeat(50));
let results = [];
// Execute pipeline stage by stage
for (let i = 0; i < pipeline.length; i++) {
const currentStage = pipeline[i];
const stageNumber = i + 1;
const currentPipeline = pipeline.slice(0, stageNumber);
console.log(`\nš Stage ${stageNumber}/${pipeline.length}:`);
console.log('Stage content:', JSON.stringify(currentStage, null, 2));
try {
const stageStartTime = Date.now();
results = await model.aggregate(currentPipeline).option({ allowDiskUse }).exec();
const stageEndTime = Date.now();
const executionTime = stageEndTime - stageStartTime;
console.log(`ā±ļø Execution time: ${executionTime}ms`);
console.log(`š Results count: ${results.length}`);
if (logResults && results.length > 0) {
console.log('š Sample result (first document):');
console.log(JSON.stringify(results[0], null, 2));
if (results.length > 1) {
console.log(`... and ${results.length - 1} more documents`);
}
}
else if (results.length === 0) {
console.log('ā No results returned from this stage');
}
}
catch (error) {
console.error(`ā Error at stage ${stageNumber}:`, error);
throw error;
}
console.log('-'.repeat(40));
}
console.log('\nā
Pipeline execution completed successfully!');
console.log(`šÆ Final result count: ${results.length}`);
return results;
}
// Export as default for easy importing
exports.default = Wrapper;