在PATCH请求期间要散列的密码

时间:2019-09-12 17:36:48

标签: express mongoose

在补丁请求期间,其他密码(例如,“姓名”和“电子邮件”,如果需要)也已更改,然后被散列。

到目前为止,我具有以下代码的补丁路由:

router.patch("/edit/:_id", (req, res, next) => {
User.findOneAndUpdate({_id : req.params._id},
    {$set:
       {
         email: req.body.email,
         name: req.body.name,
         password: req.body.password
       },
     },
     {
       new : true,
       upsert: true,
       omitUndefined: true
     }
   )
  .then(user => res.json(user))
  .catch(err => console.log(err));
});

模型/架构

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;

// Create Schema
const UserSchema = new Schema({
name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = User = mongoose.model("users", UserSchema);

我想使用“ bcryptjs”对用户密码进行哈希处理。请照亮我。提前致谢。

1 个答案:

答案 0 :(得分:0)

为了解决这个问题,我在架构上添加了findOneandUpdate预钩子。

这是代码:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
const bcrypt = require("bcryptjs");

// Create Schema
const UserSchema = new Schema({
  name: {
  type: String,
  required: true
   },
  email: {
    type: String,
    required: true,
    unique: true
   },
  password: {
    type: String,
    required: true
   },
  date: {
    type: Date,
    default: Date.now
   }
});

UserSchema.pre('findOneAndUpdate', async function (next) {
    await this.updateOne({},{ $set: { password: bcrypt.hashSync(this.getUpdate().$set.password, 10) }})
  });

module.exports = User = mongoose.model("users", UserSchema);