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

Node.js+MongoDB无法保存哈希密码,提示password路径必填

问题解决:MongoDB密码字段验证失败

错误信息

Error: User validation failed: password: Path password is required.

相关代码

用户模型代码

const {Schema, model} = require('mongoose');

const UserSchema = new Schema({
    email: {type: String, unique: true, required: true},
    password: {type: String, required: true},
    isActivated: {type: Boolean, default: false},
    activationLink: {type: String},
})

module.exports = model('User', UserSchema)

创建用户代码

const bcrypt = require('bcryptjs');
const UserModel = require('../models/user-model');
...
const hashPassword = await bcrypt.hash(password, 10);
console.log(`email => ${email} pass => ${hashPassword}`);
const user = await UserModel.create({email, hashPassword});

日志输出

email => lll@google.com pass => $2a$10$4IV2Q0ZncWHInfT89Fwl.eCxCgvykvY.uqlvq0GNSeDJ/6Q83T7nK


问题原因

用户模型定义的必填字段是password,但创建用户时传入的字段是hashPassword,字段名不匹配导致Mongoose判定password字段未提供,触发必填验证错误。

修复方案

有两种简单的修复方式:

方式1:调整创建用户时的字段映射

修改创建用户的代码,将哈希密码赋值给模型要求的password字段:

const user = await UserModel.create({email, password: hashPassword});

方式2:修改哈希后的变量名

将哈希密码的变量名直接改为password,利用对象简写语法传入:

// 注意原密码变量名避免和哈希后的重名,建议改为originalPassword
const password = await bcrypt.hash(originalPassword, 10);
console.log(`email => ${email} pass => ${password}`);
const user = await UserModel.create({email, password});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 20:10:36