简体   繁体   中英

How to post multiple Axios requests but the number of post request varies

A bit of context, I am trying to take a JSON file data and populate my MongoDB with the data. The way I am currently doing it is as such:

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

The length of the data object varies depending on the JSON file I am trying to read. An example of the data object is as such data example .
However, this method is taking too long especially if I have more than 50 JSON entries I am trying to post.
Is there another way to do this such that it can post all the data in one shot? However, it needs to take into account that the number of post requests depends on the length of the data object. I will need to match each attribute of the data object to the schema attributes, such as time, lat and LNG.

My Mongoose Model Schema where I am trying to post and populate with my data is as shown:

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;

My API Code to POST data:

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

Your server API needs to accept an array of objects.

It will be a lot faster because there would be only one network request/response between the server and the client. That also means one single axios request.

Yes, the request body would be bigger, but even if the server is reusing the same connection, it would still take more time to parse all theses incoming HTTP requests and produce as many HTTP responses.

Also there would eventually be a lot less communication with the database since all the objects can probably be inserted in a single request.

Also, you should be careful about mixing the async | await syntax with the functional style then() | catch() Promises. Choose one or the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM