Reputation: 81
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?
Upvotes: 8
Views: 4336
Reputation: 51638
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));
Upvotes: 2
Reputation: 18441
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.
Upvotes: 0