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

MERN栈向MongoDB插入数据仅生成ID其余字段为null问题求助

问题修复方案

核心问题原因

字段全部为null的问题,是前端发起POST请求时的两个错误导致的:

  • JSON.stringify使用方法错误:该方法第一个参数需要传入完整的待序列化对象,你直接传入了三个独立的状态值,最终只会序列化第一个参数firstName的值,后端无法解析到三个字段的完整数据
  • 未配置POST请求的JSON格式头:后端的express.json()中间件需要请求头携带Content-Type: application/json才能正常解析请求体

修复代码

前端React组件的addUser方法修改为以下内容:

addUser = () => {
    const requestOption = {
        method: 'POST',
        // 新增请求头,指定请求体为JSON格式
        headers: {
            'Content-Type': 'application/json'
        },
        // 将三个字段封装为对象后再序列化
        body: JSON.stringify({
            firstName: this.state.firstName,
            lastName: this.state.lastName,
            email: this.state.email
        })
    }
    fetch("http://localhost:3001/api/add", requestOption)
        .then(res => res.json())
        .then(data => console.log(data))
}

可选后端优化(非必改,仅提升性能)

你当前每次收到请求都重新建立MongoDB连接、请求结束后关闭连接的写法性能较低,可以改为服务启动时一次性建立连接,后续直接复用:

// 服务启动时先连接数据库
client.connect(err => {
    if(err) {
        throw err;
    }
    const collection = client.db('crud').collection('data');
    // 数据库连接成功后再启动接口监听
    app.post('/api/add', (req, res) => {
        const fName = req.body.firstName;
        const lName = req.body.lastName;
        const email = req.body.email;
        const storeData = {"firstName" : fName, "lastName" : lName, "email" : email};
        collection.insertOne(storeData, function(err, result) {
            res.send(result);
        });
    });
    app.listen(port, () => {
       console.log(`Application listening at http://localhost:${port}`) 
    });
})

额外小提醒:你的TextField组件中,firstName和lastName的type属性错误写成了email,可以改成text避免前端输入校验异常,这个问题不影响本次接口提交的字段存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:39:02