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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-04-28 19:56:58 +0000
Seen: 7 times
Last updated: Apr 28 '23
What is the process of integrating API data into MongoDB using Spark/Python?
How can additional fields that have been transformed be queried in MongoDB?
What is the difference between indexing in Elasticsearch and MongoDB?
When data is updated in MongoDB, why does Logstash not reflect the changes?
How can the Mongo Operator be used to deploy MongoDB in EKS/EFS?
How can data be extracted from Azure DocumentDB for exporting purposes?
How can I link or integrate mongodb with Google Data Studio?