Siddhartha Chowdhury Siddhartha Chowdhury - 7 months ago 11
Javascript Question

How to insert multiple records/rows in MySQL

Is it possible in Sails.js to insert multiple records?
I am using MySQL, I need to save 'n' rows into MySQL depending upon request coming from API.

I need help with respect to Sails.js
Thank you

Answer

Yes you can write multiple records in mysql at once. let my model is:

module.exports = {
  tableName:'test',
  autoCreatedAt:false,
  autoUpdatedAt:false,
  attributes: {
    name:'string'
  }
};

First let's see how is it done in mysql query.

INSERT INTO `test` VALUES (1,'AB'),(2,'ABCCDC');

Now this is how you can add multiple records...

Test.create([{name:'name1'},{name:'name2'},{name:'name3'}])
  .exec(function(err,done){
    if(err){
      //hendle the error;
      return;
    }
    //successfully inserted;
  });

Now i guess my point is clear.

you just have to pass the array of objects in model.create() to insert multiple objects.