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);
相关推荐
暮色妖娆丶1 分钟前
Spring 源码分析 事务管理的实现原理(下)
数据库·spring boot·spring
暮色妖娆丶1 分钟前
Spring 源码分析 事务管理的实现原理(上)
数据库·spring boot·spring
LaughingZhu15 分钟前
Product Hunt 每日热榜 | 2026-02-18
大数据·数据库·人工智能·经验分享·搜索引擎
是吕先森1 小时前
mysql基础
数据库·mysql·oracle
Zzz 小生2 小时前
LangChain Tools:工具使用完全指南
jvm·数据库·oracle
SQL必知必会3 小时前
SQL 计算百分位数和中位数
数据库·sql
亓才孓3 小时前
[SpringBoot]UnableToConnectException : Public Key Retrieval is not allowed
java·数据库·spring boot
好学且牛逼的马3 小时前
从“混沌初开”到“有序统一”:Java集合框架发展历程与核心知识点详解
前端·数据库·python
REDcker5 小时前
HDR Vivid 技术介绍
数据库·算法·视频·sdr·屏幕·显示技术·dhr
冰暮流星5 小时前
sql语句之union语句
数据库·sql