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

求助:全栈应用表单值未存入MySQL,数据库写入0

表单提交后MySQL存入0而非实际值的问题修复

核心问题定位

你的代码存在两个关键错误,导致数据库插入值异常:

  1. Patient模型的insert方法直接传入完整对象,MySQL的VALUES(?)语法无法正确解析对象结构,会将其隐式转换为0
  2. Patient构造函数存在字段赋值错误:this.pharmacy_streetname = newPatient.streetname误用了家庭地址的街道字段,而非药房街道字段

修复步骤

1. 修正Patient模型的insert方法

当前SQL插入逻辑未明确指定字段,无法正确映射对象数据。需要显式声明字段列表并提取对应值数组:

// Patient.js 中的 insert 方法
insert(values) {
    // 列出Patient表所有字段,与前端传入字段一一对应
    const fields = [
        'patient_email', 'first_name', 'last_name', 'streetname', 'city', 'state', 'zipcode',
        'sex', 'gender', 'age', 'date_of_birth', 'phone_number', 'profession', 'card_number',
        'expiration_date', 'insurance_name', 'policy_num', 'group_num', 'copay', 'pharmacy_name',
        'pharmacy_streetname', 'pharmacy_city', 'pharmacy_state', 'pharmacy_zipcode'
    ];
    // 提取对应字段的值数组
    const valuesArray = fields.map(field => values[field]);
    
    const sql = `INSERT INTO Patient (${fields.join(', ')}) VALUES (?);`;
    
    console.log(valuesArray); // 可验证值是否正确
    
    db.query(sql, [valuesArray], (err, result) => {
        if (err) throw err;
        console.log(result);
        console.log("Insert Success");
    });
}

2. 修正Patient构造函数的字段赋值错误

将药房街道字段的赋值修正为正确的数据源:

// Patient.js 中的构造函数片段
constructor(newPatient) {
    if (newPatient != null) {
        // ... 其他字段保持不变
        this.pharmacy_name = newPatient.pharmacy_name;
        this.pharmacy_streetname = newPatient.pharmacy_streetname; // 修正此处
        this.pharmacy_city = newPatient.pharmacy_city;
        this.pharmacy_state = newPatient.pharmacy_state;
        this.pharmacy_zipcode = newPatient.pharmacy_zipcode;
    }
}

3. 额外优化:确保响应与数据库操作同步

当前后端路由在插入操作未完成时就返回成功响应,建议添加回调或Promise等待操作完成:

// Register.js 中的 /patient 路由
router.post('/patient', validateToken, async (req, res) => {
    const patientData = req.body;

    try {
        await new Promise((resolve, reject) => {
            const thePatient = new Patient();
            thePatient.insert(patientData, (err) => {
                if (err) reject(err);
                else resolve();
            });
        });
        res.send("Successfully created patient profile!");
    } catch (err) {
        res.status(500).json({ error: err.message });
        console.error(err);
    }
});

同时修改insert方法支持回调:

// Patient.js 中的 insert 方法
insert(values, callback) {
    // ... 之前的fields和valuesArray代码
    db.query(sql, [valuesArray], (err, result) => {
        if (err) {
            console.error(err);
            return callback(err);
        }
        console.log(result);
        console.log("Insert Success");
        callback(null);
    });
}

验证方法

  1. 重启后端服务
  2. 提交表单后查看后端控制台打印的valuesArray,确认所有值为实际输入内容
  3. 检查MySQL数据库,确认插入数据与表单输入一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:14:54