Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trace Mongoose query execution time

I'm trying to create trace spans of my node.js with Mongoose application. One specific trace I would like to get is how long one Mongoose query, update or document.save method takes time.

What I know is that Mongoose has pre and post hooks for these methods: https://mongoosejs.com/docs/middleware.html

However I'm struggling to find a good example how to keep timer in context between the hooks so that I get the trace of one and the same operation execution. Is there a good way to accomplish this?

like image 286
Jani Siivola Avatar asked Nov 16 '25 07:11

Jani Siivola


1 Answers

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

Reference From: https://github.com/Automattic/mongoose/issues/6376#issuecomment-385083763

like image 126
Ankit Manchanda Avatar answered Nov 17 '25 20:11

Ankit Manchanda