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

提交表单后MongoDB仅保存_id和__v,数据未存储的原因排查

Why Your MongoDB Data Isn't Saving Properly

Hey there, let's break down why only _id and __v are being saved instead of your form data—there are a few key issues in your code:

1. You're Creating an Empty Client Object

In your POST route, you're initializing new Client({}) with an empty object. That means you're not passing any of the form data from req.body into the new document. MongoDB will only auto-generate the default _id and __v (version key) when saving an empty document.

2. Form Field Names Don't Match Your Schema Structure

Your Schema uses nested fields like "personal information.first name", but your form inputs have names like "First Name"—the casing, spacing, and nesting don't align. Even if you passed req.body directly, Mongoose wouldn't map the form data to the correct Schema fields.

3. You Might Not Be Parsing Form Data

If you haven't set up middleware to parse incoming form data, req.body will be empty. Without that, you can't access any of the submitted values at all.


Fixes to Get Your Data Saving Correctly

Step 1: Set Up Form Data Parsing

If you're using Express 4.16 or later, Express has built-in middleware to parse URL-encoded form data. Add this to your main app file (like app.js):

const express = require('express');
const app = express();

// Parse URL-encoded form data into req.body
app.use(express.urlencoded({ extended: true }));

This will populate req.body with all your form's submitted values.

Step 2: Align Form Fields with Your Schema (or Map Data Manually)

You have two straightforward options here:

Option A: Update Form Field Names to Match Schema Nesting

Modify your form inputs to use names that mirror your Schema's nested structure. This lets Express auto-parse the data into a nested object that Mongoose can use directly:

<label>First Name</label>
<input type="text" name="personal information[first name]" placeholder="Enter Your First Name">

<label>Second Name</label>
<input type="text" name="personal information[second name]" placeholder="Enter Your Second Name">

<!-- Example for military state fields: -->
<label>Military Service ID</label>
<input type="number" name="military state[military service ID(triple)]" placeholder="Enter ID">

Then update your POST route to pass req.body directly to the Client constructor:

app.post('/data-en', (req, res, next)=>{
  // Optional: Log req.body to verify you're receiving data
  console.log('Received form data:', req.body);

  var newClient = new Client(req.body);
  newClient.save((err)=>{
    if(err) {
      console.error('Save error:', err);
      return res.status(500).send('Failed to save data. Check console for details.');
    }
    res.send('Saved Successfully')
  })
})
Option B: Manually Map Form Data to Schema Fields

If you don't want to change your form, explicitly map each form field to the corresponding nested Schema field:

app.post('/data-en', (req, res, next)=>{
  var newClient = new Client({
    "personal information": {
      "first name": req.body["First Name"],
      "second name": req.body["Second Name"],
      // Add all other personal info fields here
    },
    "military state": {
      "full name": req.body["Full Name"], // Match your form's actual name attribute
      "birth date": req.body["Birth Date"],
      // Add all other military state fields here
    }
    // Include remaining Schema sections as needed
  });

  newClient.save((err)=>{
    if(err) {
      console.error('Save error:', err);
      return res.status(500).send('Failed to save data. Check console for details.');
    }
    res.send('Saved Successfully')
  })
})

Step 3: Debug with Console Logs

Add console.log(req.body) at the start of your POST route to confirm that the form data is being parsed correctly. If it's empty, double-check your form data parsing middleware setup.


内容的提问来源于stack exchange,提问作者Nour M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:24:03