Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use explain() in Node.js mongoose

I am trying to see The executionStats on my console but I always get undefined or [object, object]. I just have a simple query where I want to see some stats. Can someone explain why this isn’t working? If I just use my query for querying (while not using explain()) the query is successful.

This is my query when trying to use explain with all the other code. I want to see the performance of the query so I found out that the best way to get the performance time is by using explain().

  const timeFunction2 = new Promise((resolve, reject) => {
    var startTime = performance.now();

    setTimeout(() => {

      conn.collection('galery').find({ "user_id": req.session.userId}).explain("executionStats", (err, explain) => {
        console.log('MongoDebug: ' + explain[0]);
      });

      var endTime = performance.now();
      resolve(endTime - startTime);
    });
  });

  timeFunction2.then(time => {
    console.log(`${time} ms.`);
  });

And this is my query code where I can sucssessfuly get data and show them on my page

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const timeFunction2 = new Promise((resolve, reject) => {
    var startTime = performance.now();

    setTimeout(() => {


conn.collection('galery').find({ "user_id": req.session.userId}).toArray( (err, resultImg) =>{
.
.
.
});

      var endTime = performance.now();
      resolve(endTime - startTime);
    });
  });

  timeFunction2.then(time => {
    console.log(`${time} ms.`);
  });

>Solution :

You need to change how you are logging the explain object to console.

      conn.collection('galery').find({ "user_id": req.session.userId}).explain("executionStats", (err, explain) => {
        console.log('MongoDebug: ' + explain[0]);
      });

By using 'MongoDebug: ' + explain[0] you are implicitly calling .toString() on explain[0] as you are appending it to a string, so it must be a string. For objects, this converts them to [object, Object].

Instead you can pass it as a separate object to your console.log:

console.log('MongoDebug: ', explain[0]);

Or convert it to JSON with extra spacing for better readability:

console.log(JSON.stringify(explain[0], null, 2));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading