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

Express+Mongoose注册接口无法接收传入参数仅获取到ID的问题求助

Fixing Your Registration Endpoint Parameter Issue

Hey there, let's work through why your registration endpoint isn't picking up all incoming parameters. After looking over your code, I've spotted a couple of key issues that are almost certainly causing this problem:

1. Mongoose Schema Field Type Case Mismatch

The biggest culprit is in your UserSchema definition—you're using uppercase Type instead of lowercase type for your field types. Mongoose is case-sensitive here, so it doesn't recognize these field definitions correctly. This means when you try to save the new user, Mongoose can't map the req.body values to your schema fields properly, resulting in only the auto-generated ID being stored.

Here's the corrected UserSchema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const UserSchema = new Schema({
 Sass: { type: String },
 Matemp : { type : String },
 Nom : { type : String },
 Cin : { type : String },
 Prenom : { type : String },
 StartDate : { type : Date },
 Departement: { type : String },
 Username : { type : String },
 Password: { type : String },
});
module.exports = User = mongoose.model("users", UserSchema);

2. Missing Body Parsing Middleware

Another common reason req.body might be empty (or only partial) is if you haven't configured Express to parse JSON request bodies. Make sure you've added this middleware at the top of your Express app setup:

// If using Express 4.16+, use the built-in json parser
app.use(express.json());

// For older Express versions, install and use body-parser:
// const bodyParser = require('body-parser');
// app.use(bodyParser.json());

Without this middleware, Express won't parse the JSON payload from your POST request, so req.body will be undefined or empty.

3. Improper Async Handling

Your route uses async but still relies on .then() chains, and you're calling console.log("done") immediately after newUser.save() without waiting for it to complete. This can lead to race conditions where you send a response before the user is actually saved. Let's clean that up with async/await for better readability and reliability:

Corrected route code:

router.post("/register", async (req, res) => {
  try {
    // Check if user exists
    const existingUser = await User.findOne({ Username: req.body.Username });
    if (existingUser) {
      return res.status(400).json({ Username: "Email already exists" });
    }

    // Create new user
    const newUser = new User({
      Sass: req.body.Sass,
      Matemp: req.body.Matemp,
      Nom: req.body.Nom,
      Cin: req.body.Cin,
      Prenom: req.body.Prenom,
      StartDate: req.body.StartDate,
      Departement: req.body.Departement,
      Username: req.body.Username,
      Password: req.body.Password
    });

    // Save user to database
    const savedUser = await newUser.save();
    console.log("User saved successfully");
    return res.status(200).json({ msg: savedUser });
  } catch (err) {
    // Handle any unexpected errors
    console.error(err);
    return res.status(500).json({ error: "Server error occurred" });
  }
});

Steps to Test

  1. Update your UserSchema with lowercase type for all fields.
  2. Verify the body parsing middleware is added to your Express app.
  3. Replace your route code with the async/await version above.
  4. Test the registration endpoint again—you should now see all parameters being saved to the database.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:49:07