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);
相关推荐
葫芦和十三30 分钟前
图解 MongoDB 03|CRUD 全链路:一条 find 怎么穿过 WiredTiger
后端·mongodb·agent
葫芦和十三8 小时前
图解 MongoDB 04|索引模型:每建一个索引,就是在 B+-tree 森林里多栽一棵
后端·mongodb·agent
葫芦和十三1 天前
图解 MongoDB 02|BSON:你以为存的是 JSON,其实是带类型的二进制
后端·mongodb·agent
葫芦和十三1 天前
图解 MongoDB 01|文档数据库
后端·mongodb·agent
倔强的石头_2 天前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战
数据库
冬奇Lab2 天前
每日一个开源项目(第134篇):Zvec - 阿里开源的嵌入式向量数据库,向量搜索界的 SQLite
数据库·人工智能·llm
ClouGence3 天前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
无响应de神3 天前
三、用户与权限管理
数据库·mysql
✎ ﹏梦醒͜ღ҉繁华落℘4 天前
单片机基础知识---stm32单片机的优先级
stm32·单片机·mongodb
麦聪聊数据4 天前
数据服务化时代:企业数据能力输出的核心路径
数据库