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 小时前
第三阶段数据库-7:sql中函数,运算符,常用关键字
数据库·笔记·sql·学习·sqlserver·c#
牛角上的男孩4 小时前
apt update Ign and 404 Not Found
开发语言·数据库
瓜酷月..7 小时前
MySQL的高可用+MHA
数据库·mysql
差不多的张三7 小时前
【解决方案】powershell自动连接夜神adb端口
数据库·adb
小马哥编程9 小时前
【软考架构】第6章 数据库基本概念
数据库·oracle·架构
自学也学好编程9 小时前
【数据库】PostgreSQL详解:企业级关系型数据库
数据库·postgresql
.Eyes10 小时前
OceanBase 分区裁剪(Partition Pruning)原理解读
数据库·oceanbase
MrZhangBaby11 小时前
SQL-leetcode— 2356. 每位教师所教授的科目种类的数量
数据库
一水鉴天12 小时前
整体设计 之定稿 “凝聚式中心点”原型 --整除:智能合约和DBMS的在表层挂接 能/所 依据的深层套接 之2
数据库·人工智能·智能合约
翔云12345612 小时前
Python 中 SQLAlchemy 和 MySQLdb 的关系
数据库·python·mysql