如何通过单次API调用让Node.js接收Flutter列表并存入MongoDB
批量存入心率数据到MongoDB的实现方案
后端(Node.js)代码修改
直接修改现有API接口,让它支持接收整个心率列表,利用MongoDB的$push+$each操作符批量插入数组元素,替代原有的单条插入逻辑:
// 批量更新有氧训练的心率数据 routes.post('/api/batch-insert-aerobic-heartrate', async (req, res) => { try { const { uniqueId, exerciseId, heartrateList } = req.body; await User.findOneAndUpdate( { uniqueId: parseInt(uniqueId), "completed_aerobic_exercise.exerciseId": exerciseId, }, { // 用$each批量推送整个心率数组 $push: { "completed_aerobic_exercise.$.heartrateAerobicList": { $each: heartrateList.map(item => ({ value: parseInt(item.value), date: item.date })) }, } }, { new: true } // 可选:返回更新后的文档,方便调试 ) res.send("批量心率数据已成功存入"); } catch(error) { console.error("批量插入心率数据出错:", error.message); res.status(500).send("服务器内部错误"); } });
核心要点:
$each是MongoDB专门用于批量添加数组元素的操作符,完美匹配你的批量上传需求- 对心率列表里的每个
value做parseInt转换,保证和数据库中的数值类型一致 - 新增错误状态码返回,让前端能明确识别请求失败的情况
前端(Flutter)代码修改
前端需要把心率列表打包成数组,通过JSON格式发送给后端(不能直接传数组到请求body,必须转成JSON字符串):
// 构造心率列表(示例) List<Map<String, dynamic>> heartrateList = [ {"value": "78", "date": "2022-08-03 18:09:51.073324"}, {"value": "82", "date": "2022-08-03 18:10:01.073324"}, {"value": "85", "date": "2022-08-03 18:10:11.073324"}, // ... 更多心率数据 ]; var url = Uri.parse('https://dummy.herokuapp.com/api/batch-insert-aerobic-heartrate'); var response = await http.post( url, headers: {"Content-Type": "application/json"}, // 声明请求为JSON格式 body: jsonEncode({ "uniqueId": "${widget.userId}", "exerciseId": widget.exeID, "heartrateList": heartrateList, }), ); // 处理响应 if (response.statusCode == 200) { print("批量上传成功"); } else { print("上传失败:${response.body}"); }
核心要点:
- 添加
Content-Type请求头,告诉后端接收的是JSON数据 - 用
jsonEncode将包含数组的对象转为JSON字符串,确保后端能正确解析心率列表
内容的提问来源于stack exchange,提问作者DarciFo
相关产品推荐
相关产品推荐

