Node.js Knex.js:如何使用for循环插入多个数据?

Node.js Knex.js:如何使用for循环插入多个数据?,node.js,knex.js,Node.js,Knex.js,我是一个新手,尝试用node&knex构建一个web应用程序 请想象我有一个从前端发送的对象数组,我需要将所有数据插入数据库,数组结构如下: [ { dateTime: 'Aug 08 2019 12:00', event_id: '57' }, { dateTime: ' Aug 09 2018 12:00', event_id: '57' } ] 表结构如下所示: 我的想法是使用循环和异步等待函数来完成这项工作 我能够使用以下代码插入第一个元素: addDateTime(dateArra

我是一个新手,尝试用node&knex构建一个web应用程序

请想象我有一个从前端发送的对象数组,我需要将所有数据插入数据库,数组结构如下:

[ { dateTime: 'Aug 08 2019 12:00', event_id: '57' },
{ dateTime: ' Aug 09 2018 12:00', event_id: '57' } ]
表结构如下所示:

我的想法是使用循环和异步等待函数来完成这项工作

我能够使用以下代码插入第一个元素:

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");
        }
addDateTime(日期数组){
for(设i=0;i
但当我尝试使用for loop和async wait函数时,我非常困惑和迷茫

到目前为止,我提出的代码不成功:

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);
}
addDateTime(日期数组){
log(日期数组);
异步函数插入(dateArray){
试一试{
for(设i=0;i

谢谢。

您不需要在这里循环,因为
knex(…)。insert
可以很容易地接受数组。因此,您需要这样的东西:

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);
    }
}
请记住,由于您的
insert
是一个
async
函数,因此必须使用
await
调用它,所以最后一行应该是
await insert(dateArray);
,这很可能是您的主要问题