簡體   English   中英

在 Mongoose 'pre' & 'post' 鈎子中獲取請求標識符

[英]Getting request identifier in Mongoose 'pre' & 'post' hooks

我正在使用 Mongoose(最新版本),類型腳本(NestJS)。

我正在使用“前”和“后”掛鈎收集有關我們查詢的一些指標,以測量查詢時間(包括.network 延遲)。 我添加了一個“pre”掛鈎,它應該啟動一個計時器,該計時器將在“post”掛鈎中停止。 缺少的一件事是每個請求的唯一標識符,我可以將其設置為“pre”掛鈎中的鍵,並使用此鍵在“post”掛鈎中識別請求。

由於某種原因,請求上似乎沒有這樣的標識符。

我試圖使用$locals字段設置我自己的標識符,但它未定義,所以它不起作用。

有任何想法嗎?

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

嘗試與next參數一起使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM