Mongoose: Query times in mongoose

Created on 21 Apr 2018  路  6Comments  路  Source: Automattic/mongoose

Do you want to request a feature or report a bug?
feature

What is the current behavior?
N/A

If the current behavior is a bug, please provide the steps to reproduce.
N/A

What is the expected behavior?
A way to log the time taken by each mongoose query

Context:
We recently had an issue where our mongo instances were thrashing because we were running a really large and slow query. The size of the query itself was about 5MB and it was taking minutes to execute. I would like to look at each query that we send to mongo and log something if the time taken by the query is above a threshold. The mongoose.('debug', () => {}); only allows to log the query before it's sent, but no way to find the time taken by the query

Please mention your node.js, mongoose and MongoDB version.
node: v8.9.1
mongoose: 4.11.11
mongo: 3.4

Most helpful comment

schema.pre('find', function() {
  this._startTime = Date.now();
});

schema.post('find', function() {
  if (this._startTime != null) {
    console.log('Runtime in MS: ', Date.now() - this._startTime);
  }
});

All 6 comments

Hi @vkarpov15, thanks for the reply. Just wondering if there are any examples of using query middleware, as I am not exactly clear on how this would work.

Also, I would have to set a timer in the pre middleware and have it available in the post, not sure if just setting it on this would actually persist

schema.pre('find', function() {
  this._startTime = Date.now();
});

schema.post('find', function() {
  if (this._startTime != null) {
    console.log('Runtime in MS: ', Date.now() - this._startTime);
  }
});

Thanks @vkarpov15, I should have replied earlier. I tried that and it worked. Thanks for your help

Happy to help :beers:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

weisjohn picture weisjohn  路  3Comments

adamreisnz picture adamreisnz  路  3Comments

ghost picture ghost  路  3Comments

Soviut picture Soviut  路  3Comments

adamreisnz picture adamreisnz  路  3Comments