Mongoose Morgan Logger
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.
Common errors
-
TypeError: morgan.token is not a function
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.fixUpgrade `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. -
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.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`.fixUpgrade `mongoose-morgan` to version `1.0.12` or higher. This version sets `useNewUrlParser` and `useUnifiedTopology` to `true` by default, resolving these deprecation warnings. -
MongooseError: The `dbName` option is required when using `mongodb+srv` connections.
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.fixUpgrade `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' }`.
Warnings
- gotcha Older versions of `mongoose-morgan` (prior to `v1.0.12`) might emit deprecation warnings from Mongoose regarding `useNewUrlParser` and `useUnifiedTopology`.
- gotcha 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.
- gotcha 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.
- gotcha 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.
Install
-
npm install mongoose-morgan -
yarn add mongoose-morgan -
pnpm add mongoose-morgan
Imports
- morgan
const morgan = require('mongoose-morgan');import morgan from 'mongoose-morgan';
- mongooseMorgan
import { morgan } from 'mongoose-morgan';import * as mongooseMorgan from 'mongoose-morgan';
- MorganMiddleware
import type { MorganMiddleware } from 'mongoose-morgan';
Quickstart
import express from 'express';
import morgan from 'mongoose-morgan';
import mongoose from 'mongoose';
const app = express();
const port = process.env.PORT || 8080;
// Ensure MongoDB connection for mongoose-morgan
// In a real app, you'd typically connect Mongoose once at app startup.
// For simplicity here, mongoose-morgan handles its own connection based on connectionString.
app.use(morgan({
connectionString: process.env.MONGO_URI || 'mongodb://localhost:27017/logs-db'
}));
app.get('/', (req, res) => {
res.send('Hello World! Check your MongoDB logs.');
});
app.get('/error', (req, res) => {
res.status(500).send('An error occurred.');
});
// Close Mongoose connection on app shutdown (optional, but good practice)
process.on('SIGINT', async () => {
await mongoose.disconnect();
console.log('MongoDB connection disconnected through app termination');
process.exit(0);
});
app.listen(port, () => {
console.log(`Server running on port ${port}. Visit http://localhost:${port}`);
});