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

Mongoose操作MongoDB时表单数据仅存储ID的问题排查

解决Mongoose仅保存_id字段,其他表单数据未入库的问题

问题描述

使用Mongoose提交表单数据到MongoDB时,数据库中仅生成_id字段,其他输入字段均未保存,已检查Schema和表单配置但未定位到问题。

项目代码

const bodyParser = require("body-parser");
const express = require("express");
const path = require("path");
//const hbs=require("hbs");
const app = express();
const mongoose = require("mongoose");
require("./db/conn");
const Index = require("./models/index_schema");
const Doctor = require("./models/doctor_schema");
const Enterdetails = require("./models/enterdetails_schema");

const port = process.env.PORT || 80;

// Set the public directory as the static folder
app.use(express.static(path.join(__dirname, "public")));

app.use(express.urlencoded({ extended: false }));
app.use(express.urlencoded({ extended: true }));
// Middleware setup
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Serve index.html
app.get("/", (req, res) => {
  return res.sendFile(path.join(__dirname, "public", "index.html"));
});

//create a new user in database
app.post("/index", async (req, res) => {
  try {
    const indexSchema = new Index({
      name: req.body.name,
      phone_number: req.body.phone_number,
      password: req.body.password,
    });

    const userphn = await Index.findOne({ phone_number: req.body.mobile_number });

    if (!userphn) {
      return res.send("User not found"); // Send an error response if the user is not found
    }

    await indexSchema.save();
    console.log(indexSchema);
    res.status(201).redirect("index.html"); // Send a success response if everything is fine
  } catch (error) {
    res.status(400).send(error);
    console.log(error);
  }
});

// Serve enterdetails.html
app.get("/enterdetails.html", (req, res) => {
  return res.sendFile(path.join(__dirname, "public", "enterdetails.html"));
});

// Redirect to enterdetails.html
app.get("/open-enterdetails-page", (req, res) => {
  res.redirect("/enterdetails.html");
});

app.post("/enterdetails", async (req, res) => {
  try {
    const enterdetailsData = new Enterdetails({
      name: req.body.name,
      age: req.body.age,
      blood_group: req.body.blood_group,
      phone_number: req.body.phone_number,
      date: req.body.date,
      medical_history: req.body.medical_history,
      password: req.body.password,
    });
    console.log("Body: ", req.body);
    await enterdetailsData.save();
    console.log(enterdetailsData);
    res.status(201).send("/enterdetails.html");
  } catch (error) {
    res.status(400).send(error);
    console.log(error);
  }
});

// Serve doctor.html
app.get("/doctor.html", (req, res) => {
  return res.sendFile(path.join(__dirname, "public", "doctor.html"));
});

// Redirect to doctor.html
app.get("/open-doctor-page", (req, res) => {
  res.redirect("/doctor.html");
});

// post request for doctor.hbs
app.post("/doctor", async (req, res) => {
  try {
    const doctorSchema = new Doctor({
      name: req.body.name,
      phone_number: req.body.phone_number,
      password: req.body.password,
    });

    await doctorSchema.save();
    console.log(doctorSchema);
    res.status(201).redirect("/doctor.html");
  } catch (error) {
    res.status(400).send(error);
    console.log(error);
  }
});

app.listen(port, () => {
  console.log(`server is running at port no ${port}`);
});

排查与修复步骤

1. 清理重复的解析中间件

代码重复注册了express.urlencoded和body-parser,可能导致请求体解析异常。Express 4.16+已内置body-parser功能,保留一套即可:

// 替换原中间件代码
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

2. 修复/index路由的逻辑错误

该路由存在逻辑矛盾:创建新用户实例后,却查询req.body.mobile_number(但实例中用的是phone_number),且如果用户不存在就返回错误,随后还保存空的新实例。根据需求调整逻辑:

  • 如果是注册接口:先检查用户是否已存在,再创建保存新用户
  • 如果是登录接口:不要创建新实例,直接验证用户后跳转

示例注册逻辑:

app.post("/index", async (req, res) => {
  try {
    // 检查手机号是否已注册
    const existingUser = await Index.findOne({ phone_number: req.body.phone_number });
    if (existingUser) {
      return res.send("该手机号已注册");
    }
    // 创建并保存新用户
    const newUser = new Index({
      name: req.body.name,
      phone_number: req.body.phone_number,
      password: req.body.password,
    });
    await newUser.save();
    console.log(newUser);
    res.status(201).redirect("index.html");
  } catch (error) {
    res.status(400).send(error);
    console.log(error);
  }
});

3. 验证Model的Schema定义

确保你的Schema文件(如index_schema.js)中定义了所有需要保存的字段,且字段名与后端req.body的键完全一致:

// models/index_schema.js 示例
const mongoose = require('mongoose');
const indexSchema = new mongoose.Schema({
  name: { type: String, required: true },
  phone_number: { type: String, required: true },
  password: { type: String, required: true }
});
module.exports = mongoose.model('Index', indexSchema);

如果Schema未定义某个字段,Mongoose会自动忽略该字段的保存。

4. 检查前端表单的name属性

确认表单输入框的name属性与后端req.body使用的键完全匹配,例如:

<form action="/index" method="POST">
  <input type="text" name="name" placeholder="姓名">
  <input type="text" name="phone_number" placeholder="手机号">
  <input type="password" name="password" placeholder="密码">
  <button type="submit">提交</button>
</form>

5. 确认请求体数据是否正确接收

在每个POST路由中打印req.body,验证后端是否正确获取到表单数据:

console.log("接收到的表单数据:", req.body);

如果打印结果为空或字段缺失,检查表单提交方式(必须是POST)、编码类型(默认application/x-www-form-urlencoded即可)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:14:59