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
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));