1

I am using Mongoose (latest version), Type script (NestJS).

I am working on collecting some metrics about our queries using 'pre' & 'post' hooks to measure the query time (including the network latency). I have added a 'pre' hook that should start a timer that will be stopped in the 'post' hook. The one thing that is missing is a unique identifier of each request, that I could set as a key in the 'pre' hook and identify the request in the 'post' hook using this key.

For some reason, it seems that there is no such an identifier on the request.

I was trying to set an identifier of my own using the $locals field but it is undefined so it doesn't works.

Any ideas?

let count = 0;
UserSchema.pre(/.*/, async function () {
  this.$locals.requestId = count; // getting undefined error since locals doesn't exists

  console.log(`Pre - Request id: ${this.$locals.requestId}`);

  count += 1;
});

UserSchema.post(/.*/, function () {
  console.log(`Post - Request id: ${this.$locals.requestId}`);
});
Roy Leibovitz
  • 579
  • 5
  • 16
  • Would you please share the part of your code to show how you're working with `$locals`? – Mostafa Fakhraei Dec 28 '22 at 13:08
  • @MostafaFakhraei let count = 0; // eslint-disable-next-line func-names UserSchema.pre(/.*/, async function () { this.$locals.requestId = count; console.log(`Pre - Request id: ${this.$locals.requestId}`); count += 1; }); // eslint-disable-next-line func-names UserSchema.post(/.*/, function () { console.log(`Post - Request id: ${this.$locals.requestId}`); }); – Roy Leibovitz Dec 28 '22 at 14:05
  • @MostafaFakhraei I have added my code to the question – Roy Leibovitz Dec 28 '22 at 14:11
  • The code seems fine, I've used `$locals` before and I'm pretty sure the issue is not related to the mongoose. However, have you tried to take `next` from the `pre` callback function and execute it right after the `count` increments? – Mostafa Fakhraei Dec 28 '22 at 14:29
  • Can you share an example for that? – Roy Leibovitz Dec 28 '22 at 14:47

1 Answers1

0

Try to use with next parameter:

let count = 0;
UserSchema.pre('save', function (next) {
  this.$locals.requestId = count;
  console.log(`Pre - Request id: ${this.$locals.requestId}`);
  count += 1;
  next();
})
Mostafa Fakhraei
  • 3,409
  • 3
  • 11
  • 25