1 | initial version |
There are a few ways to record MongoDB/Mongoose queries in an Express request-response cycle:
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
});
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);
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.