You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js+MongoDB登录API密码哈希未生成问题排查请求

密码哈希未生效的问题排查与修复

我是Node.js和MongoDB新手,正在开发登录API,尝试添加密码哈希功能但密码未被加密插入。请帮我检查以下Model和添加学生代码中的错误:

原Model代码

const mongoose = require("mongoose")
var Schema  = mongoose.Schema;


var studentSchema = new Schema(
    {
        name: {
                type:String,
                required: true
        },
        address: {
            type:String,
            required: true
        },
        phone: {
            type:Number,
            required: true
        },
        password:{
            type: String,
            trim: true,
            required : true
        }

    }
)


 studentSchema.pre("save",async function(next){
    const student = this;
 if(user.isModified("password"))
 {
    student.password = await bcrypt.hash(student.password,8)
}
 next()

 })
module.exports =mongoose.model('student',studentSchema);

原添加学生接口代码

router.post('/student/create', async(req,res)=>{
   
    const student = new studentModel(req.body)
    try{
            await student.save();
            res.status(201).send(
                {
                    "status" : true,
                    "message" : "Student Created!!!!!!!!!!!!!!!!"
                });
    }
    catch(error)
    {
        res.status(400).send(error);

    }


});

错误分析

  • 未引入bcrypt依赖:Model中调用了bcrypt.hash()但未导入bcrypt库,也未安装该依赖,直接导致哈希逻辑无法执行,甚至会触发运行时错误。
  • pre-save钩子变量名错误:钩子内定义了const student = this,但判断密码是否修改时却用了未定义的user.isModified("password"),导致条件永远不成立,哈希代码块完全不会被执行。
  • (潜在规范问题)next调用时机:虽然当前代码因await不会引发异步问题,但建议确保哈希操作完成后再调用next(),避免逻辑混乱。

修正后的代码

步骤1:安装bcrypt依赖

npm install bcrypt

步骤2:修正Model代码

const mongoose = require("mongoose");
const bcrypt = require("bcrypt"); // 引入bcrypt库
var Schema = mongoose.Schema;

var studentSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  address: {
    type: String,
    required: true
  },
  phone: {
    type: Number,
    required: true
  },
  password: {
    type: String,
    trim: true,
    required: true
  }
});

studentSchema.pre("save", async function(next) {
  const student = this;
  // 修正变量名,使用当前实例student进行判断
  if (student.isModified("password")) {
    student.password = await bcrypt.hash(student.password, 8);
  }
  next(); // 确保逻辑完成后触发后续流程
});

module.exports = mongoose.model('student', studentSchema);

步骤3:添加学生接口(无需修改,仅优化提示语)

router.post('/student/create', async(req,res)=>{
   
    const student = new studentModel(req.body)
    try{
            await student.save();
            res.status(201).send({
                "status" : true,
                "message" : "学生创建成功!"
            });
    }
    catch(error)
    {
        res.status(400).send(error);
    }
});

内容的提问来源于stack exchange,提问作者John Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:52:54