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);
相关推荐
酸菜牛肉汤面几秒前
17、什么是脏读?幻读?不可重复读?
java·数据库·mysql
ClouGence1 分钟前
数据实时迁移同步工具 CloudCanal-v5.3.1.0 发布,支持金仓数据库
大数据·数据库·mysql·数据分析·dba
怪我冷i1 分钟前
GORM 的 Migration API
数据库·postgresql·golang·ai编程·ai写作
Miss_Chenzr7 分钟前
Springboot快递信息管理52c05本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot
醉卧考场君莫笑8 分钟前
数据分析理论基础
java·数据库·数据分析
czlczl2002092515 分钟前
MybatisPlusInterceptor实现无感修改SQL的底层原理(源码)
数据库·spring boot·后端·sql
yumgpkpm17 分钟前
银行的数据智能平台和Cloudera CDP 7.3(CMP 7.3)的技术对接
数据库·人工智能·hive·hadoop·elasticsearch·数据挖掘·kafka
optimistic_chen25 分钟前
【Redis 系列】常用数据结构---String类型
数据结构·数据库·redis·缓存·string
大猫子的技术日记29 分钟前
Redis 快速上手实战教程:从零搭建高性能缓存系统
数据库·redis·缓存
莳花微语30 分钟前
记录一次生产中mysql主备延迟问题处理
数据库·mysql