Insert array of records into mysql with Node JS
Asked Answered
P

1

7

I have a array of data something like

var records = [
               {Name: '', Id: 1},
               {Name: '', Id: 2},
               {Name: '', Id: 3},
               {Name: '', Id: 4},
               {Name: '', Id: 5},
               {Name: '', Id: 6}
              ];

there could be thousands of items inside records array...

Ques1: Can we create a stored procedure which will accept an array of objects in mysql?

Ques2: Is there a way to bulk insert this data into mysql with Node JS?

Phylum answered 15/11, 2015 at 19:17 Comment(0)
A
7

You can bulk insert the array of records ,but before that you might need to convert it into array of arrays

I use array reduce to get an array something like this

let j=[
               {Name: '', Id: 1},
               {Name: '', Id: 2},
               {Name: '', Id: 3},
               {Name: '', Id: 4},
               {Name: '', Id: 5},
               {Name: '', Id: 6}
              ];

              let values=j.reduce((o,a)=>{
                    let ini=[];
                    ini.push(a.Name);
                    ini.push(a.Id);
                    o.push(ini);
                    return o
              },[])
              console.log(values);

This will output

[["",1],["",2],["",3],["",4],["",5],["",6]]

Now inserting into the mysql database

1-Using normal callback

const con=require('./mysql.js'); //mysql connectionin mysql.js 

var sql = "INSERT INTO customers (name, id) VALUES ?";
con.query(sql, [values], function (err, result) { //pass values array (from above)  directly here
    if (err) throw err;
    console.log("Number of records inserted: " + result.affectedRows);
  });
});

so the format of multiple data insert should be like [[[a,b],[b,c],[d,k]]]

2-Using promises

var Promise = require("bluebird");//for promises
const promisecon=Promise.promisifyAll(require('./mysql.js'));//
  var sql = "INSERT INTO customers (name, id) VALUES ?";
    promisecon.queryAsync(sql,[values]).then((result)=>{//bluebird identifies with Async
      console.log(result);
    }).catch(function(err){
        console.log(err);
      })

3-Using async await

 var sql = "INSERT INTO customers (name, id) VALUES ?";
async function build() {
            try {
              const result =await con.queryAsync(sql,[values]);

                 console.log(result);

            } catch (err) {
              // do something
            }
          }
          build();
Acciaccatura answered 27/1, 2019 at 11:41 Comment(3)
Is there any way to get the list of insertIDs as result?Blodgett
you mean the primary keys that are created after insertion? @MoeFarAcciaccatura
Yup, I was looking for something like thatBlodgett

© 2022 - 2024 — McMap. All rights reserved.