Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert array of records into mysql with Node JS

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?

like image 294
Kalyan Chakravarthy S Avatar asked Nov 15 '15 19:11

Kalyan Chakravarthy S


1 Answers

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();
like image 68
Shubh Avatar answered Sep 28 '22 01:09

Shubh