log all queries that mongoose fire in the application

node.jsMongodbMongoose

node.js Problem Overview


I have application using nodejs and mongodb. I have used mongoose for ODM. Now i want to log all the queries that mongoose fire during the whole application.

How to log these?

node.js Solutions


Solution 1 - node.js

You can enable debug mode like so:

mongoose.set('debug', true);

or add your own debug callback:

mongoose.set('debug', function (coll, method, query, doc [, options]) {
 //do your thing
});

This will log all executed collection methods and their arguments to the console.

Solution 2 - node.js

You can use the following format:

mongoose.set("debug", (collectionName, method, query, doc) => {
	console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});

or any other logger of your choice:

mongoose.set("debug", (collectionName, method, query, doc) => {
	logger(`${collectionName}.${method}`, JSON.stringify(query), doc);
});

Solution 3 - node.js

I'm using node bunyan, this is an option to debug and track queries(may help someone else)

function serializer(data) {
    let query = JSON.stringify(data.query);
    let options = JSON.stringify(data.options || {});

    return `db.${data.coll}.${data.method}(${query}, ${options});`;
}

let log = bunyan.createLogger({
    name: 'AppName',
    src: false,
    serializers: {
        // ...
        dbQuery: querySerializer
        // ...
    },
    // ...
});

mongoose.set('debug', function(coll, method, query, doc, options) {
    let set = {
        coll: coll,
        method: method,
        query: query,
        doc: doc,
        options: options
    };

    log.info({
        dbQuery: set
    });
});

Solution 4 - node.js

You can also set debug logger parameters:

node index.js DEBUG=mquery

but this will only log queries, not insert or update statements.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncodeofnodeView Question on Stackoverflow
Solution 1 - node.jsmr.freezeView Answer on Stackoverflow
Solution 2 - node.jsVithal ReddyView Answer on Stackoverflow
Solution 3 - node.jslesterzoneView Answer on Stackoverflow
Solution 4 - node.jsZilvinasView Answer on Stackoverflow