mongoose-profiling-middleware is a utility package for Node.js applications that integrates with Mongoose to leverage MongoDB's native profiling capabilities. It automatically injects the current source file and line number as a `$comment` into every Mongoose query executed against a MongoDB instance. This feature allows developers to easily identify the exact code location responsible for slow or frequent database operations when analyzing the MongoDB `system.profile` collection. The current stable version, 1.0.2, offers a straightforward, side-effect-based integration. This middleware simplifies the process of identifying performance bottlenecks by automating query annotation, distinguishing it from manual comment insertion. Its primary function is to provide immediate context for database query performance, thereby aiding optimization efforts without requiring significant application code changes.
npm install mongoose-profiling-middlewareVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up Mongoose, load the profiling middleware, and execute several Mongoose operations that will be annotated with source code comments for MongoDB profiling.
Profile in controlled environments first. When profiling in production, monitor database performance metrics closely and disable profiling when not actively debugging.
Review existing Mongoose queries and middleware to ensure they do not rely on a custom `$comment` field if you intend to use this profiling middleware.
Place `require('mongoose-profiling-middleware');` immediately after `mongoose.connect()` completes and before your application starts making database queries.Ensure `require('mongoose-profiling-middleware');` is placed in your code *after* `mongoose.connect()` has been called and your Mongoose models have been defined.In a MongoDB shell, connect to your database and run `db.setProfilingLevel(1)` to profile slow operations, or `db.setProfilingLevel(2)` to profile all operations. Remember to set the level for the correct database.