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);
相关推荐
MatrixOrigin3 小时前
数据库没有死,只是范式变了
数据库·oracle
羊小蜜.4 小时前
Mysql 13: 触发器全解——创建、查看、使用与注意事项
数据库·mysql·触发器
阿里加多5 小时前
第 1 章:Go 并发编程概述
java·开发语言·数据库·spring·golang
ShiJiuD6668889995 小时前
Mysql 进阶
数据库·mysql
一 乐5 小时前
物流信息管理|基于springboot + vue物流信息管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·物流信息管理系统
Rick19935 小时前
Redis 分布式锁:核心使用场景
数据库·redis·分布式
身如柳絮随风扬6 小时前
Redis如何实现高效插入大量数据
数据库·redis·缓存
Dream of maid6 小时前
Mysql(3)运算符
数据库·mysql·adb