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

在Express.js中使用Mongoose创建用户时部分字段缺失的问题排查

问题解决:Mongoose创建用户时部分字段无法映射

问题根源是Mongoose模型中的字段拼写错误:你在Schema里把firstName写成了firtName,导致req.body.firstName的数据无法和模型字段匹配,自然无法存入数据库。

修正后的模型代码

const mongoose = require('mongoose')
const { Schema } = mongoose

const userModel = new Schema({
   firstName: { // 修正拼写错误
     type: String,
     required: true
   },
   lastName: {
     type: String,
     required: true
   },
   email: {
     type: String,
     required: true
   },
   password: {
     type: String,
     required: true
   },
   phone: {
     type: Number,
     required: true
   }
})

const User = mongoose.model('User', userModel) // 用const声明避免全局变量污染
module.exports = User

控制器代码的额外修正

你的控制器代码还有两个小问题需要调整:

  1. newUser.save()的then回调参数用了res,和外层的响应对象重名,会导致后续无法正确调用响应方法;
  2. 响应消息里的Successfullt是拼写错误,应为Successfully。

修正后的控制器代码:

let newUser = new User({
  firstName: req.body.firstName,
  lastName: req.body.lastName,
  email: req.body.email,
  password: req.body.password,
  phone: req.body.phone,
})

bcrypt.genSalt(10, (err, salt) => {
  bcrypt.hash(newUser.password, salt, (err, hash) => {
    if (err) {
      return res.status(500).json({ error: err}); // 加return避免后续代码执行
    }
    newUser.password = hash;
    newUser.save()
     .then(savedUser => { // 重命名参数,避免和res冲突
       res.status(200).json({ message: 'Successfully created' }) // 修正拼写错误
    })
    .catch((err) => {
      res.status(500).json({ error: err});
    })
 })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:45:56