Node JS Inserting array of objects to mysql database when using transactions

Dennis Wanyonyi

Am using node-mysql to add records to a database but am facing a challenge when the records to be inserted are an array of objects and I need the operation to be a transaction. I have simplified my problem by creating a test project to better explain my problem.

Lets say I have to tables users and orders and the data to be inserted looks like this

var user = {
   name: "Dennis Wanyonyi",
   email: "[email protected]"
};

var orders = [{
   order_date: new Date(),
   price: 14.99
}, {
   order_date: new Date(),
   price: 39.99
}];

I want to first insert a user to the database and use the insertId to add the each of the orders for that user. Am using a transaction since in case of an error, I want to rollback the whole process. Here is how I try to insert all the records using node-mysql transactions.

connection.beginTransaction(function(err) {
  if (err) { throw err; }
  connection.query('INSERT INTO users SET ?', user, function(err, result) {
    if (err) {
      return connection.rollback(function() {
        throw err;
      });
    }


    for (var i = 0; i < orders.length; i++) {

      orders[i].user_id = result.insertId;

        connection.query('INSERT INTO orders SET ?', orders[i], function(err, result2) {
          if (err) {
            return connection.rollback(function() {
              throw err;
            });
          }  
          connection.commit(function(err) {
            if (err) {
              return connection.rollback(function() {
                throw err;
              });
            }
            console.log('success!');
          });
        });
       }
      });
     });

However I have a problem iterating over the array of orders without having to call connection.commit multiple times within the for loop

Sagar Gopale

I would suggest to construct a simple string for multiple row insert query for orders table in the for loop first and then execute it outside the for loop. Use the for loop to only construct the string. So you can rollback the query whenever you want or on error. By multiple insert query string i mean as follows:

INSERT INTO your_table_name
    (column1,column2,column3)
VALUES
    (1,2,3),
    (4,5,6),
    (7,8,9);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Inserting JSON objects into mySQL database using node.js

ER_PARSE_ERROR when inserting row into MySQL database using node.js

Emoji are not inserting in database node js mysql

POSTING an array of objects to node.js/save to database using mongoose

Node.js puppeteer mysql - Inserting fetched values in database inside a loop using mysql

Inserting array into MySQL database

PHP not inserting array into MySQL database

Iterating json array objects using node js

Error when connecting mysql database with node js

Inserting an array to mysql using php

Handling rollbacked MySQL transactions in Node.js

save array of objects to the mongo database using node, express

How to inform and update a client when a new record inserted in mysql database using node js and socket.io

Issue on Inserting JavaScript Array Data into MySQL Database

Inserting parts of a multidimensional array into a mysql database

Inserting an Array from HTML form into MYSQL Database

Inserting mysql database results into a multidimensional array in php

MySQL: Integrity error when inserting into database

Syntax error in mysql when inserting an image into a database

Error when inserting array value into database

Inserting records into MySQL with node.js

Trouble with inserting integer into MySQL Database using PHP

Inserting millions of records into MySQL database using Python

Issue in inserting data into mysql database using php

Problems inserting data into MYSQL database using PHP

error in inserting data to mysql database using javafx

Issue inserting data into MySQL database using php

Inserting data into mysql database using checkboxes php

MySQL inserting a new user into a database using nodejs