简体   繁体   中英

Mutate Request Body using Mongoose Middleware

I'm wondering how do I mutate or change the request body of the End-User before finally update and save the document in mongoose? like this 'save' event of mongoose middleware

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

I just want it, to do like this so

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

I was just searching about the documents of mongoose and it does not fulfill my questions in my mind, so the reason I explore and I properly solve it without another execution by

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

I hope, it helps :)

You can export the function inside the pre-save middleware, and use that function in your controllers, inside the route itself when updating the document and saving it, ex:

// 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)
  })

This is one solution.

Both routes in the example above will salt and hash the password. This moves the logic from the models (middlewares) to the controllers.

For the coding style, this is not the best style... But since Mongoose is an everyday pain, it's not a problem. 👍

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM