0101
0101

Reputation: 2707

NodeJS - How to insert multiple rows to MySQL

I am trying to insert several (hundres/thousands) of records to MySQL database. My problem is that I am not really sure what's the best way how do it. Example:

function saveData(data, callback) {
    var dataLength = data.length,
        saved = [];

    for (var i = 0; i < dataLength; i++) {
        db.query("INSERT INTO table VALUES (?, ?, ?)", data[i], function(err, res) {
           if (err) {
              // ...
           }

           saved.push(res.insertId);
        });
    }
}

The problem is that after all data is saved (save[] contains all IDs) I need to pass this array to a callback. Obviously I can't do it immediately... I have to wait for all queries to be done.

The questions: Should I use for loop or is it better to do it recursively (Next insert will be called after previous is done), should I check if saved.length === dataLength and then return the array or is there some better way how to do it?

Upvotes: 2

Views: 5847

Answers (1)

mscdex
mscdex

Reputation: 106698

Here's how you might do it with async:

function saveData(data, cb) {
  async.mapSeries(data, function(queryData, callback) {
    db.query("INSERT INTO table VALUES (?, ?, ?)", queryData, function(err, res) {
      if (err)
        callback(err);
      else
        callback(null, res.insertId);
    });
  }, cb);
  // cb will be passed `err, saved`
}

Upvotes: 2

Related Questions