Getting request identifier in Mongoose 'pre' & 'post' hooks

261 Views Asked by At

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

There are 1 best solutions below

3
Mostafa Fakhraei On

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