Log all queries using mongodb native driver for Node JS
Asked Answered
U

2

8

Im relatively new to the MongoDB. At first I used mongoose, but now I decided to abandon it. Immediately I ran into the following problem: I can't understand how to print all the performed queries to the console.

In mongoose this could be done as simple as to write mongoose.set('debug', true), but how to do that using native driver?

I've read about Logger in the dcumentation, but the output seems completely unreadable for me. Is it possble to tune the output or i should just parse that somehow?

Unscientific answered 8/11, 2019 at 18:9 Comment(0)
R
2

The Logger class no longer logs queries in version 4.0. You can do this instead:

const uri = "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
const client = new MongoClient(uri, { monitorCommands:true });
client.on('commandStarted', (event) => console.debug(event));
client.on('commandSucceeded', (event) => console.debug(event));
client.on('commandFailed', (event) => console.debug(event));
Retroversion answered 7/6, 2022 at 20:26 Comment(0)
T
0

You should use the mongo's Logger class (see the official API doc):

const connect = async () => {
    console.log("Connecting to database...");

    try {
        let client = await MongoClient.connect(uri, opts);
        console.log("Database connected.");

        Logger.setLevel("debug");
        console.log("MongoDB Logger set to DEBUG");
    } catch (e) {
        console.log("ERROR: " + e.message);
    }
};

The Logger class has multiple options (info, debug, error). They will log different types of database actions/events.

Tabloid answered 1/4, 2020 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.