Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log all queries that mongoose fire in the application

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?

like image 447
codeofnode Avatar asked Sep 12 '13 10:09

codeofnode


People also ask

Can Mongoose queries be chained?

The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.

What does model find () return in Mongoose?

mongoose .find() method returns object with unwanted properties. 12. Model.findOne not returning docs but returning a wrapper object.

What are the applications of Mongoose?

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

What is Mongoose projection?

In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.


2 Answers

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.

like image 163
mr.freeze Avatar answered Sep 20 '22 04:09

mr.freeze


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); }); 
like image 41
Vithal Reddy Avatar answered Sep 20 '22 04:09

Vithal Reddy