Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knex.js: How to insert Multiple data with a for loop?

I'm new to coding trying to build a web app with node & knex.

Please imagine I have a array of object send from front-end, and I need to insert all the data into database, the array structure like:

[ { dateTime: 'Aug 08 2019 12:00', event_id: '57' },
{ dateTime: ' Aug 09 2018 12:00', event_id: '57' } ]

and the table structure are like:

table structure

My thought was to use for loop & async await function to do the job,

I was able to insert the first element with the following code:

addDateTime(dateArray) {

        for (let i = 0; i < dateArray.length; i++) {
            let tempDateTime = new Date(dateArray[i].dateTime)

            return this.knex(dateTimes).insert({
                date: tempDateTime.toDateString(),
                start_time: tempDateTime.toTimeString().replace("GMT+0800", ""),
                iso_string: tempDateTime.toISOString(),
                event_id: dateArray[i].event_id
            }).returning("event_id");
        }

But when I try use for loop & async await function, I was pretty confuse & lost.

The code I come up with so far unsuccessful:

addDateTime(dateArray) {

    console.log(dateArray);

    async function insert(dateArray) {
        try{
            for (let i = 0; i < dateArray.length; i++) {
                let tempDateTime = new Date(dateArray[i].dateTime)

                await this.knex(dateTimes).insert({
                    date: tempDateTime.toDateString(),
                    start_time: tempDateTime.toTimeString().replace("GMT+0800", ""),
                    iso_string: tempDateTime.toISOString(),
                    event_id: dateArray[i].event_id
                }).returning("event_id");
            }
        } catch (err) {
            console.log(err);
        }
    }

    insert(dateArray);
}

Thank you.

like image 726
plat123456789 Avatar asked Oct 28 '22 08:10

plat123456789


1 Answers

You don't really need to loop here since knex(...).insert can easily accept an array. So, you need something like this:

async function insert(dateArray) {
    try {
        const data = dateArray.map(x => {
            const tempDateTime = new Date(x.dateTime);

            return {
                date: tempDateTime.toDateString(),
                start_time: tempDateTime.toTimeString().replace("GMT+0800", ""),
                iso_string: tempDateTime.toISOString(),
                event_id: x.event_id
            };
        });

        await this.knex(dateTimes).insert(data);
    } catch (err) {
        console.log(err);
    }
}

Just remember that since your insert is an async function, you have to call it with await, so your last line should be await insert(dateArray); and that's what most probably was your main issue.

like image 177
bredikhin Avatar answered Nov 15 '22 07:11

bredikhin