You need to enable JavaScript to run this app. 使用Mongoose操作MongoDB无法保存数据,求代码修改建议
优惠活动
大模型
产品
解决方案
定价
更多

使用Mongoose操作MongoDB无法保存数据,求代码修改建议

问题排查与修改建议

以下是你代码里的问题和对应修改方案:

  • Pug模板层级错误(首要问题)
    Pug 完全依靠缩进判断标签嵌套关系,你当前代码里所有输入框、提交按钮和form标签是平级,不属于表单内容,提交时不会携带任何参数,后端直接触发参数校验失败逻辑,不会执行保存操作。
  • 缺少Express请求体解析配置
    Express默认不解析POST表单的urlencoded格式请求体,如果你没加对应中间件配置,req.body会是undefined,同样拿不到表单提交的字段。
  • 可选优化:age字段类型兼容
    表单提交的age值默认是字符串格式,虽然Mongoose会自动转换为Number类型,提前做类型转换可以避免异常。

修改后的完整代码

后端代码(先在所有路由前加解析中间件)

// 新增:Express请求体解析配置,必须放在/person路由定义之前
app.use(express.urlencoded({ extended: true }));

var personSchema = mongoose.Schema({
    name: String,
    age: Number,
    nationality: String
});
 
var Person = mongoose.model("Person", personSchema);
app.post('/person', function(req, res){
    var personInfo = req.body;
    // 可选:把age转成数字,避免字符串转义异常
    personInfo.age = Number(personInfo.age);
    
    if(!personInfo.name || isNaN(personInfo.age) || !personInfo.nationality){
       res.render('show_message', {
          message: "Sorry, you provided wrong info", type: "error"});
    } else {
       var newPerson = new Person({
          name: personInfo.name,
          age: personInfo.age,
          nationality: personInfo.nationality
       });
         
       newPerson.save(function(err, Person){
          if(err) {
             // 排查时可以加console.log(err)打印具体错误
             res.render('show_message', {message: "Database error", type: "error"});
          } else {
             res.render('show_message', {
                message: "New person added", type: "success", person: personInfo});
          }
       });
    }
});

Pug模板代码(修正缩进)

html
    head
        title Document
    body
      form(action="/person", method="POST")
        div
           label(for="name") Name: 
           input(name="name")
        br
        div
           label(for="age") Age: 
           input(name="age")
        br
        div
           label(for="nationality") Nationality: 
           input(name="nationality")
        br
        button(type="submit") Create new person 

修改完成后重新启动服务提交表单即可正常保存数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 01:57:01