Skip to content Skip to sidebar Skip to footer

Issue Inserting Values In A Loop (for) In The Database : Same Value Is Inserted - Node Js / Sql

I try to insert some data into a database inside a loop. The issue is that it inserts always the same value (the first one). I mean even if the value of my variable is different (I

Solution 1:

The loop completely executes before the callbacks given to the asynchronous functions are called.

A solution is to trap the array items in a closure, for exemple using forEach:

obj.productEntities.forEach(function(entity){
    global.store_urls.push(entity.url);
    var reference = entity.IdProduct;
    ...

Note also that the whole loop is still executed before the queries are made, which might be a problem if the code that follows depends on the DB being updated. In such a case you'd better have a look at modern solutions for handling asynchronous tasks:


Solution 2:

Exactly its due to async nature. For loop will be executed Async.

So try the following:

    var obj = JSON.parse(result.body);
    global.store_urls = [];
var async = require('async');

    async.forEach(obj.productEntities, function(callback){
   // do your logic
  In this part 

connection.query('INSERT INTO `vd_tendance` VALUES ( NULL , ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP())',
                  [ reference,
                    type_1,
                    brand,
                    price,
                    new_price,
                    reduction,
                    sold,
                    url,
                  ]
              , function (err, result) {
                  if (err) {console.error('error inserting into database : ' + err.stack); return;}
                  else{
                     callback() ---------------------->Iterate the loop
                  }
              });
            }
          });


   )};

Post a Comment for "Issue Inserting Values In A Loop (for) In The Database : Same Value Is Inserted - Node Js / Sql"