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);
相关推荐
tod1135 分钟前
Redis 持久化机制深度解析(RDB / AOF)
数据库·redis·缓存
❀͜͡傀儡师14 分钟前
一个基于PostgreSQL的轻量级消息队列(PGMQ)
数据库·postgresql·pgmq
哈库纳玛塔塔23 分钟前
dbVisitor 统一数据库访问库,更新 v6.7.0,面向 AI 支持向量操作
数据库·spring boot·orm
object not found1 小时前
uniCloud 数据库:database() 和 databaseForJQL() 到底有什么区别?
数据库
zhangyueping83851 小时前
1、MYSQL-DDL
数据库·mysql
xdpcxq10291 小时前
EF Core实体追踪Entry中记录的数据
服务器·数据库·oracle
忧郁的橙子.1 小时前
02-嵌入模型和向量数据库
数据库·embedding
kaoa0002 小时前
Linux入门攻坚——67、MySQL数据库-4
linux·运维·数据库·mysql
学Linux的语莫2 小时前
skills的使用
java·数据库·python
码云数智-园园2 小时前
MySQL 性能调优实战:高效处理 ORDER BY 与 GROUP BY 查询
数据库·mysql