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

Express+Mongoose注册时密码字段无法写入MongoDB求助

用户注册时密码字段无法写入MongoDB的问题

问题描述

在基于Express和Mongoose的项目中实现用户注册功能时,其他字段(name、email)均可正常存入MongoDB,但密码字段无法正确写入。已使用bcrypt对密码进行哈希处理,怀疑问题出在函数逻辑或Schema配置中,但无法定位具体原因。

相关代码

服务器代码

const express = require('express')
const colors = require('colors')
const dotenv = require('dotenv').config()
const {errorHandler} = require('./middleware/errorMiddleware')
const connectDB = require('./config/db')
const PORT = process.env.PORT || 5000

// 连接数据库
connectDB()

const app = express()

app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', (req, res) => {
    res.status(200).json({message: 'Welcome to the support desk api'})
})

app.use('/api/users', require('./routes/userRoutes'))

app.use(errorHandler)

app.listen(PORT, () => console.log(`Port started on ${PORT}`))

Mongoose Schema

const mongoose = require('mongoose')

const userSchema = mongoose.Schema({
    name : {
        type: String,
        required: [true, 'Please enter your name']
    },
    email : {
        type: String,
        required: [true, 'Please add an email'],
        unique: true
    },
     password : {
        type: String,
        required : [true, 'Please add a password'],
     },
    isAdmin : {
        type: Boolean,
        required : true,
        default: false,
    }
},
{
    timestamps: true
})

module.exports = mongoose.model('User', userSchema)

用户注册逻辑代码

const asyncHandler = require('express-async-handler')
const bcrypt = require('bcryptjs')
const User = require('../models/userModel')

// @desc 注册新用户
// @route api/users
// @access Public
const registerUser = asyncHandler(async (req, res) => {
    const {name, email, password} = req.body

    // 验证字段是否齐全
    if(!name || !email || !password) {
        res.status(400)
       throw new Error('Please include all fields')
    }

    // 检查用户是否已存在
    const userExists = await User.findOne({email})

    if (userExists){
        res.status(400)
        throw new Error('User already Exist')
    }

    // 哈希密码
    const salt = await bcrypt.genSalt(10)
    const hashedPassword = await bcrypt.hash(password, salt)

    // 创建用户
    const user = await User.create({
        name,
        email,
        hashedPassword, // 此处为问题所在
    })

    if(user) {
        res.status(201).json({
            _id: user._id,
            name: user.name,
            email: user.email
        })
    } else {
        res.status(400)
        throw new Error('Invalid user Data')
    }
})

// @desc 用户登录
// @route api/users/login
// @access Public
const loginUser = asyncHandler(async (req, res) => {
    res.send('Login Route')
})

module.exports = {
    registerUser,
    loginUser
}

Postman请求结果

请求成功返回201状态码,响应包含用户的_id、name、email字段,但查看MongoDB数据库发现,新创建的用户文档中password字段为空,未存储哈希后的密码值。

解决方案

核心问题

注册逻辑中创建用户时,传入的键是hashedPassword,但Mongoose Schema定义的密码字段是password,两者不匹配,导致数据库无法识别该字段,因此密码未被写入。

修改代码

在registerUser函数的User.create部分,将hashedPassword替换为password: hashedPassword,修改后的代码如下:

// 创建用户
const user = await User.create({
    name,
    email,
    password: hashedPassword, // 修正字段名匹配Schema
})

验证

修改后重新测试注册功能,查看MongoDB数据库,用户文档的password字段会正确存储哈希后的密码值,同时前端响应仍不包含密码字段,符合安全规范。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:40:34