如何发布多个Axios请求,但发布请求的数量各不相同



关于上下文,我正在尝试获取JSON文件数据并用数据填充MongoDB。我目前的做法是:

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")
});
}

数据对象的长度因我试图读取的JSON文件而异。数据对象的示例就是这样的数据示例
但是,此方法花费的时间太长,尤其是当我要发布50个以上的JSON条目时
是否有其他方法可以做到这一点,以便它可以在一次拍摄中发布所有数据?但是,需要考虑发布请求的数量取决于数据对象的长度。我需要将数据对象的每个属性与模式属性相匹配,例如时间、lat和LNG。

我试图发布和填充数据的Mongoose模型模式如下所示:

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;

我的API代码到POST数据:

app.post("/createRawGeopoints", async (req, res) => {
const geopoint = req.body;
const newGeopoint = new RawGeopointsModel(geopoint);
await newGeopoint.save();
res.json(geopoint)
})

您的服务器API需要接受一个对象数组。

它会快得多,因为服务器和客户端之间只有一个网络请求/响应。这也意味着只有一个axios请求。

是的,请求主体会更大,但即使服务器重用相同的连接,解析所有传入的HTTP请求并生成尽可能多的HTTP响应仍然需要更多的时间。

此外,由于所有对象可能都可以插入到一个请求中,因此最终与数据库的通信将大大减少。

此外,您应该小心将async|await语法与函数样式then()|catch()Promises混合使用。选择其中一个。

最新更新