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);
相关推荐
Andy Dennis1 小时前
一文漫谈数据库存储之索引(B+, B-link, LSM tree等)
数据库·b+树·lsm-tree
CHANG_THE_WORLD1 小时前
字符串定义的汇编分析
汇编·数据库
数据知道2 小时前
PostgreSQL:如何通过progres_fdw跨库关联查询?
数据库·postgresql
v***57002 小时前
MYSQL 创建索引
数据库·mysql
heimeiyingwang2 小时前
大模型 RAG 技术原理与企业级落地实践
大数据·数据库·人工智能·架构
倔强的石头_4 小时前
【金仓数据库】ksql 指南(七) —— 启动和管理事务(KingbaseES 数据一致性保障)
数据库
志栋智能4 小时前
自动化运维真的只能选复杂平台吗?
运维·网络·数据库·人工智能·自动化
LaughingZhu4 小时前
Product Hunt 每日热榜 | 2026-02-17
大数据·数据库·人工智能·经验分享·搜索引擎
树码小子5 小时前
Mybatis(16)Mybatis-Plus条件构造器(1)
数据库·mybatis-plus
翔云1234565 小时前
在MySQL中,出现Executed_Gtid_Set 乱序增长的场景
数据库·mysql