簡體   English   中英

使用 Mongoose 中間件修改請求正文

[英]Mutate Request Body using Mongoose Middleware

我想知道如何在最終更新並將文檔保存在貓鼬中之前改變或更改最終用戶的請求正文? 像貓鼬中間件的“保存”事件

schema.pre('save', async function () {
  const salt = await bcrypt.genSalt();
  this.password = await bcrypt.hash(this.password, salt);
});

我只是想要它,這樣做

schema.pre('updateOne', async function () {
  const salt = await bcrypt.genSalt();
  this.password = await bcrypt.hash(this.password, salt);
});

我只是在搜索 mongoose 的文件,它並沒有解決我的問題,所以我探索的原因並在沒有再次執行的情況下正確解決了它

schema.pre('updateOne', async function () {
  let data = this.getUpdate();
  const salt = await bcrypt.genSalt();
  data.password = await bcrypt.hash(data.password, salt);
});

我希望,它有幫助:)

您可以在 pre-save 中間件中導出該函數,並在更新文檔並保存它時在您的控制器、路由本身內部使用該函數,例如:

// file: saltHash.js
const bcrypt = require('bcrypt')

async function saltHash(str){
   const salt = await bcrypt.genSalt();
   const hash = await bcrypt.hash(str, salt);
   return hash
}
module.exports = saltHash

// file: usersRoutes.js
const saltHash = require('../utils/saltHash.js')
router.
  route('/users/:id').patch((req, res, next)=> {
   // the code, and then:
   if(req.body.password) req.body.password = saltHash(req.body.password)
   UserModel.findByIdAndUpdate(req.params.id, req.body)
  })

router
  .route('/users')
  .post((req, res, next) => {
     if(req.body.password) req.body.password = saltHash(req.body.password)
     UserModel.create(req.body)
  })

這是一種解決方案。

上面示例中的兩個路由都會對密碼進行加鹽和哈希處理。 這會將邏輯從模型(中間件)轉移到控制器。

對於編碼風格,這不是最好的風格......但由於貓鼬是一種日常的痛苦,所以這不是問題。 👍

暫無
暫無

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

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