Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are a few ways to record MongoDB/Mongoose queries in an Express request-response cycle:

  1. Using the Mongoose built-in debugging tool: By setting the debug flag to true when connecting to the database, all queries and updates will be logged to the console.
const mongoose = require('mongoose');
mongoose.set('debug', true);

mongoose.connect('mongodb://localhost/test', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});
  1. Using a custom logger: Create a logger middleware function in your Express app that logs the queries as they are executed. You can use the Mongoose pre and post hooks to intercept and log queries before and after they are executed.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });

const logger = (req, res, next) => {
  // intercept queries before they are executed
  mongoose.connection.on('opening', () => {
    console.log(`[${req.method}] ${req.originalUrl}`);
  });

  // intercept queries after they are executed
  mongoose.connection.on('query', (query) => {
    console.log(query);
  });

  next();
};

app.use(logger);
  1. Using a third-party package: There are a few npm packages that can be used to log MongoDB queries, such as express-mongo-sanitize and express-mongo-dblogger. These packages provide middleware functions that can be added to your Express app to log queries automatically.
const express = require('express');
const mongoose = require('mongoose');
const mongoSanitize = require('express-mongo-sanitize');

mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });
const app = express();

app.use(mongoSanitize({
  logger: (query) => {
    console.log(query);
  }
}));

Regardless of the method used, recording MongoDB/Mongoose queries in an Express request-response cycle can help with debugging, performance optimization, and security.