1.
npm i bcryptjs
主要方法如下
const password = 'Red12345!' const hashedPassword = await bcrypt.hash(password, 8)
hash方法中设置8次权衡了安全与速度
const isMatch = await bcrypt.compare('red12345!', hashedPassword) console.log(isMatch)
compare方法直接比较 plain text password 和 hashed password ,如果一致则返回true
2.
因为要在 User model 中引入 pre 中间件,所以设置 userSchema object,调用 userSchema.pre 方法
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
},
password: {
type: String,
required: true,
},
});
userSchema.pre("save", async function(next) {
const user = this;
if (user.isModified("