Express + MongoDB 实现新增用户密码加密

使用 bcryptjs 依赖实现用户加密。

1. 安装依赖

bash 复制代码
npm install bcryptjs

2. 定义用户模型

创建一个 `userModel.js` 文件,在其中定义用户模型,并在保存用户信息时对密码进行加密

javascript 复制代码
const mongoose = require("mongoose");

const bcrypt = require("bcryptjs");

// 定义用户信息的 Schema

const userSchema = new mongoose.Schema({

  username: {

    type: String,

    required: true,

    unique: true,

  },

  password: {

    type: String,

    required: true,

  },

});

// 在保存用户信息前对密码进行加密

userSchema.pre("save", async function (next) {

  const user = this;

  // 只有当密码字段被修改时才进行加密操作

  if (!user.isModified("password")) return next();

  // 生成盐,盐的复杂度为 10

  const salt = await bcrypt.genSalt(10);

  // 使用盐对密码进行哈希处理

  const hash = await bcrypt.hash(user.password, salt);

  // 将加密后的密码赋值给用户的密码字段

  user.password = hash;

  next();

});

// 定义一个比较密码的方法

userSchema.methods.comparePassword = async function (candidatePassword) {

  return await bcrypt.compare(candidatePassword, this.password);

};

// 创建用户模型

module.exports = new mongoose.model("User", userSchema);
相关推荐
又是忙碌的一天7 分钟前
SpringMVC响应
java·服务器·数据库
W001hhh17 分钟前
260110
java·数据库
冰暮流星35 分钟前
sql语句之select语句的基本使用
数据库·sql·mysql
水冗水孚1 小时前
告别黑盒!手写Windows版简易NodeMON,学习文件监听代码修改与进程服务重启知识
node.js·express
vyuvyucd1 小时前
插件式开发:C++与C#实战指南
java·前端·数据库
少云清1 小时前
【性能测试】3_性能测试基础 _指标
运维·服务器·数据库·性能测试·性能测试指标
+VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue物流配送中心信息化管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·小程序·课程设计
列御寇2 小时前
MongoDB分片集群——集群组件概述
数据库·mongodb
七夜zippoe2 小时前
领域驱动设计在Python中的实现:从理论到生产级实践
数据库·python·sqlite·ddd·pydantic
小CC吃豆子2 小时前
Qt的信号与槽机制
开发语言·数据库·qt