{"id":16652,"library":"mongoose-morgan","title":"Mongoose Morgan Logger","description":"mongoose-morgan is an npm package designed to integrate Express.js HTTP request logging (via morgan) directly into a MongoDB database (via mongoose). The current stable version is 1.0.17, which primarily focuses on updating dependencies to maintain compatibility and security. Historically, the package has seen irregular but focused feature additions, such as support for capped collections and improved handling of MongoDB Atlas connection strings. Its key differentiator is simplifying the process of persisting detailed HTTP access logs into a NoSQL database, offering configurable options for the target collection, user authentication, and advanced MongoDB connection parameters without requiring separate setup for both logging and database interaction. It's a pragmatic choice for Express applications already utilizing Mongoose for data persistence that need a straightforward way to store request logs.","status":"active","version":"1.0.17","language":"javascript","source_language":"en","source_url":"https://github.com/nemanjapetrovic/mongoose-morgan","tags":["javascript","morgan","log","logger","mongo","mongodb","error","express","http","typescript"],"install":[{"cmd":"npm install mongoose-morgan","lang":"bash","label":"npm"},{"cmd":"yarn add mongoose-morgan","lang":"bash","label":"yarn"},{"cmd":"pnpm add mongoose-morgan","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides the HTTP request logging middleware.","package":"morgan"},{"reason":"Handles MongoDB connection and schema management.","package":"mongoose"}],"imports":[{"note":"While the package's examples use CommonJS `require`, ESM `import` is the modern approach. The default export is the middleware function.","wrong":"const morgan = require('mongoose-morgan');","symbol":"morgan","correct":"import morgan from 'mongoose-morgan';"},{"note":"If your linter or TypeScript configuration has issues with the default import, importing as a namespace object is an alternative, though less common for single-function modules.","wrong":"import { morgan } from 'mongoose-morgan';","symbol":"mongooseMorgan","correct":"import * as mongooseMorgan from 'mongoose-morgan';"},{"note":"Although types were reverted to `any` in v1.0.15, for potential future-proofing or if external type definitions are used, this is the pattern for type imports.","symbol":"MorganMiddleware","correct":"import type { MorganMiddleware } from 'mongoose-morgan';"}],"quickstart":{"code":"import express from 'express';\nimport morgan from 'mongoose-morgan';\nimport mongoose from 'mongoose';\n\nconst app = express();\nconst port = process.env.PORT || 8080;\n\n// Ensure MongoDB connection for mongoose-morgan\n// In a real app, you'd typically connect Mongoose once at app startup.\n// For simplicity here, mongoose-morgan handles its own connection based on connectionString.\n\napp.use(morgan({\n    connectionString: process.env.MONGO_URI || 'mongodb://localhost:27017/logs-db'\n}));\n\napp.get('/', (req, res) => {\n    res.send('Hello World! Check your MongoDB logs.');\n});\n\napp.get('/error', (req, res) => {\n    res.status(500).send('An error occurred.');\n});\n\n// Close Mongoose connection on app shutdown (optional, but good practice)\nprocess.on('SIGINT', async () => {\n    await mongoose.disconnect();\n    console.log('MongoDB connection disconnected through app termination');\n    process.exit(0);\n});\n\napp.listen(port, () => {\n    console.log(`Server running on port ${port}. Visit http://localhost:${port}`);\n});","lang":"typescript","description":"This example sets up an Express application to log all incoming HTTP requests to a MongoDB database using `mongoose-morgan`. It demonstrates basic usage with a connection string and two example routes to generate logs."},"warnings":[{"fix":"Upgrade to `mongoose-morgan@1.0.12` or higher, which defaults these options to `true` to suppress the warnings. If you cannot upgrade, manually pass `{ useNewUrlParser: true, useUnifiedTopology: true }` in the `connectionOptions` parameter if it were exposed (it's not directly exposed in the main function signature, but rather handled internally).","message":"Older versions of `mongoose-morgan` (prior to `v1.0.12`) might emit deprecation warnings from Mongoose regarding `useNewUrlParser` and `useUnifiedTopology`.","severity":"gotcha","affected_versions":"<1.0.12"},{"fix":"Be aware that type checking will be minimal for `mongoose-morgan`'s configuration. Consider creating your own declaration file (`.d.ts`) or casting the configuration object if strong typing is critical.","message":"The TypeScript types for `mongoose-morgan` were explicitly changed from `object` to `any` in `v1.0.15` due to an issue, significantly reducing type safety for TypeScript users.","severity":"gotcha","affected_versions":">=1.0.15"},{"fix":"Upgrade to `mongoose-morgan@1.0.7` or newer, which introduced a `dbName` option in the `mongoData` configuration to explicitly specify the database name for `mongodb+srv` connections.","message":"When connecting to MongoDB Atlas using the `mongodb+srv` URI scheme, specifying the database name directly in the connection string might not work as expected. Before `v1.0.7`, `dbName` had to be handled carefully.","severity":"gotcha","affected_versions":"<1.0.7"},{"fix":"Ensure you are using `mongoose-morgan` versions `1.0.6` or `1.0.8` or newer, as this issue was fixed and then re-fixed.","message":"Versions `1.0.7` and some very early `1.0.x` releases had a bug where the `morgan.token` function was missing or improperly handled, preventing custom token definitions.","severity":"gotcha","affected_versions":"1.0.7, <1.0.6"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Upgrade `mongoose-morgan` to version `1.0.8` or a more recent version (e.g., `1.0.17`) to get the fix for the `morgan.token` functionality.","cause":"Using `mongoose-morgan` version `1.0.7` or a very early `1.0.x` version (prior to `1.0.6`) which had a bug related to `morgan.token` availability.","error":"TypeError: morgan.token is not a function"},{"fix":"Upgrade `mongoose-morgan` to version `1.0.12` or higher. This version sets `useNewUrlParser` and `useUnifiedTopology` to `true` by default, resolving these deprecation warnings.","cause":"This warning originates from Mongoose, indicating an older parser is being used. `mongoose-morgan` versions prior to `1.0.12` did not explicitly set `useNewUrlParser` or `useUnifiedTopology`.","error":"DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect."},{"fix":"Upgrade `mongoose-morgan` to version `1.0.7` or newer and use the `dbName` property within the `mongoData` configuration object: `{ connectionString: 'mongodb+srv://user:pass@cluster...', dbName: 'yourDatabaseName' }`.","cause":"Attempting to connect to MongoDB Atlas (or another `mongodb+srv` URI) with `mongoose-morgan` versions older than `1.0.7` without correctly specifying the database name in the connection string or via the `dbName` option.","error":"MongooseError: The `dbName` option is required when using `mongodb+srv` connections."}],"ecosystem":"npm"}