如何根据数据量批量发送Axios请求高效导入MongoDB数据
批量导入JSON数据到MongoDB的优化方案
当前问题
我读取JSON文件数据导入MongoDB时,采用逐个发送POST请求的方式实现,代码如下:
for (let i = 0; i < data.length; i++) { await Axios.post("http://localhost:8080/createRawGeopoints", { time: data[i].time, lat: data[i].lat, lng: data[i].lng }).then((response) => { console.log("Posted") }); }
但当数据条目超过50条时,这种方式耗时过长。我需要一种一次性批量提交所有数据的方法,要适配data对象的长度,同时保证每个数据的time、lat、lng字段与Mongoose Schema的属性匹配。
现有代码
Mongoose Schema定义
const mongoose = require('mongoose'); const RawGeopointSchema = new mongoose.Schema({ time: { type: String, required: true, }, lat: { type: Number, required: true, }, lng: { type: Number, required: true, }, }, { versionKey: false }); const RawGeopointModel = mongoose.model("raw-geopoints", RawGeopointSchema) module.exports = RawGeopointModel;
接收POST请求的API
app.post("/createRawGeopoints", async (req, res) => { const geopoint = req.body; const newGeopoint = new RawGeopointsModel(geopoint); await newGeopoint.save(); res.json(geopoint) })
优化方案
1. 修改后端API支持批量插入
Mongoose提供了insertMany()方法,可一次性插入多条文档,效率远高于逐条保存。修改API如下:
app.post("/createRawGeopoints/batch", async (req, res) => { try { const geopoints = req.body; // 批量插入并自动校验Schema字段 const result = await RawGeopointModel.insertMany(geopoints); res.status(201).json({ message: `成功插入${result.length}条数据`, data: result }); } catch (error) { res.status(400).json({ message: "批量插入失败", error: error.message }); } })
insertMany()会自动根据Schema校验每条数据的字段类型和必填项,不符合要求的数据会被拦截并返回错误。
2. 修改前端批量发送请求
直接将整个data数组作为请求体发送,无需循环逐条请求:
// 若data中每个元素已包含time、lat、lng字段,直接发送 await Axios.post("http://localhost:8080/createRawGeopoints/batch", data) .then((response) => { console.log(response.data.message); }) .catch((error) => { console.error("批量提交失败:", error.response.data); });
如果data中存在多余字段,可先做映射处理确保字段匹配:
const formattedData = data.map(item => ({ time: item.time, lat: item.lat, lng: item.lng })); await Axios.post("http://localhost:8080/createRawGeopoints/batch", formattedData) .then(res => console.log(res.data.message)) .catch(err => console.error(err));
额外优化建议
- 若数据量极大(如上万条),可分批次插入(比如每1000条发送一次请求),避免单次请求数据量过大导致超时或内存问题。
- 后端可添加事务处理(MongoDB 4.0+支持),确保批量插入要么全部成功,要么全部回滚,避免部分插入的异常情况。
内容的提问来源于stack exchange,提问作者DumplingDius
相关产品推荐
相关产品推荐

