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);
相关推荐
我不会插花弄玉13 分钟前
4.数据类型【由浅入深-MySQL】
数据库·mysql
denggun1234522 分钟前
yield
前端·数据库·python
ltl32 分钟前
SQLite Rollback Journal:写前拷贝与提交点
数据库
ltl1 小时前
TiFlash Learner:Raft 日志如何进列存
数据库
ltl1 小时前
BM25 与 Lucene Similarity:公式如何落到 postings
数据库
ltl1 小时前
RocksDB Block Cache 与 Bloom Filter:读放大怎么裁
数据库
deli0070072 小时前
JSON 树形查看器:粘贴即解析,折叠展开一目了然
前端·数据库·json·ai编程
国科安芯3 小时前
轨道供电韧性:ASP4644四通道降压架构在低轨卫星平台电源管理中的适用性分析
运维·网络·数据库·嵌入式硬件·架构·状态模式·低轨卫星星座
破土士V3 小时前
MySQL基础知识集合
数据库·mysql
笃行3503 小时前
达梦 VS 金仓:数据库替换项目里,迁移工具的差距体现在哪一层
数据库