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);
相关推荐
hehelm10 分钟前
IO 多路复用 — Reactor
linux·服务器·网络·数据库·c++
农村小镇哥17 分钟前
如何限定IP访问Oracle数据库
数据库·tcp/ip·oracle
cfm_291435 分钟前
SpringBoot 数据库全栈整合
数据库·spring boot·后端
是上好佳佳佳呀43 分钟前
MySQL 基础:从数据库概念到表结构管理DDL
数据库·mysql
Nturmoils1 小时前
Oracle 迁移评估时,我把这两类问题列在了检查清单最前面
数据库
Database_Cool_1 小时前
数据库性能不够用,升级到什么方案好?阿里云 PolarDB(云原生数据库领导者,兼容 MySQL/PostgreSQL/Oracle)平滑升级与百倍弹性
数据库·阿里云·云原生
程序猿秃头之路1 小时前
DDD 系列:聚合和聚合根详解
数据库·oracle·ddd·领域驱动设计
chatexcel1 小时前
不用写 SQL,如何用AI直连数据库生成可刷新的数据看板?ChatExcel的一种实践
大数据·数据库·人工智能·sql·数据分析·excel
码上上班2 小时前
Mongodb课程
数据库·mongodb
农村小镇哥2 小时前
Oracle中的锁和10704对高级队列锁
数据库·oracle