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);
相关推荐
踩着两条虫10 分钟前
VTJ.PRO 在线应用开发平台的数据库与基础设施
数据库·架构·nestjs
!停21 分钟前
C++入门基础—类和对象3
java·数据库·c++
llilian_1625 分钟前
ptp从时钟 ptp授时模块 如何挑选PTP从时钟授时协议模块 ptp从时钟模块
数据库·功能测试·单片机·嵌入式硬件·测试工具
municornm31 分钟前
【MySQL】to_date()日期转换
数据库·mysql
流星白龙1 小时前
【MySQL】6.MySQL基本查询(1)
数据库·windows·mysql
夕除1 小时前
Mysql--11
数据库·mysql
❀͜͡傀儡师1 小时前
docker部署WhoDB开源轻量级数据库管理工具
数据库·docker·开源
皙然1 小时前
Redis八大核心数据类型详解:从底层实现到实战落地
数据库·redis·bootstrap
时光追逐者2 小时前
一款免费、简单、高效的在线数据库设计工具
数据库·mysql·oracle·sql server
another heaven2 小时前
【软考 2026 最新版 NoSQL 数据库全分类】
数据库·nosql