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);
相关推荐
m0_748231316 分钟前
Redis简介、常用命令及优化
数据库·redis·缓存
xiaolin033318 分钟前
【复习】Redis
数据库·redis·缓存
林林总肿37 分钟前
后端mySQL很容易犯的bug,bug记录解决
数据库·mysql·bug
m0_748254091 小时前
Spring Boot 中使用 @Transactional 注解配置事务管理
数据库·spring boot·sql
宋发元2 小时前
数据库的MVCC如何理解?
数据库·oracle
圣心2 小时前
Ollama Linux 部署指南
linux·数据库·mysql
有冠希没关系2 小时前
QT 读取sqlite3数据库中文乱码
数据库·qt·sqlite
阿志iiii3 小时前
【Java毕业设计】商城购物系统(附源码+数据库脚本)
java·数据库·课程设计
南宫文凯3 小时前
hbase集群部署
大数据·数据库·hbase
shepherd枸杞泡茶3 小时前
第4章 4.4 EF Core数据库迁移 Add-Migration UpDate-Database
数据库·c#·asp.net·.net·.netcore