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 小时前
Redis热点Key独立集群实现方案
数据库·redis·缓存
laocooon5238578861 小时前
mysql,100个题目。
数据库·sql·mysql
Web极客码1 小时前
如何在Ubuntu服务器上安装和配置BIND9
服务器·数据库·ubuntu
W001hhh2 小时前
数据库实训Day004上午
数据库
funfan05172 小时前
【运维】MySQL数据库全量备份与恢复实战指南:从入门到精通
运维·数据库·mysql
+VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue在线音乐播放系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
tq10863 小时前
通用数据引用表示法:基于协议-URI-JSONPath的简洁数据定位规范
数据库
+VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue律师咨询系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
manuel_897573 小时前
六 系统安全
网络·数据库·系统安全
液态不合群4 小时前
【面试题】MySQL 三层 B+ 树能存多少数据?
java·数据库·mysql