繁体   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