Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log all queries using mongodb native driver for Node JS

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?

like image 481
AgaDeoN Avatar asked May 29 '26 20:05

AgaDeoN


1 Answers

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));
like image 117
JW. Avatar answered Jun 01 '26 08:06

JW.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!