1

I am getting empty array outside of for loop while i am appending variable in loop

let data_info1 = '';
for (let i = 0; i < data.length; i++) {
    var query = { '_id': mongoose.Types.ObjectId(data[i].coin_id) };
    var coin_data = coin_model.find(query, function (err, info) {
        var a = {}
        a['coin_name'] = info[0].coin_code;
        a['data_info'] = data[i];

        var myJsonString = JSON.stringify(a);
        data_info1 += JSON.parse(myJsonString);
    });
}
console.log(data_info1)
Waleed Iqbal
  • 1,308
  • 19
  • 35
Sarus Crane
  • 336
  • 3
  • 17

2 Answers2

3

You have a problem in JSON.parse/stringify, it's not necessary during the loop =/

Looks like that way will be better:

let data_info1 = [];
for (let i = 0; i < data.length; i++) {
    var query = { '_id': mongoose.Types.ObjectId(data[i].coin_id) };
    var coin_data = coin_model.find(query, function (err, info) {
        var obj = {
            coin_name: info[0].coin_code,
            data_info: data[i]
        };

        data_info1.push(obj);
    });
}
console.log(JSON.stringify(data_info1))

Also, the question is coin_model.find is sync or async? If it's async, it's not possible to console.log right after the loop, it will show empty result =(

In case if it's async, you need to structure your code slightly different and understand principles of async coding in JS (for example with Promises).

const promiseList = [];
for (let i = 0; i < data.length; i++) {
    var query = { '_id': mongoose.Types.ObjectId(data[i].coin_id) };

    promiseList.push(new Promise(function(resolve, reject) {
        coin_model.find(query, function (err, info) {
            if (err) reject(err);

            var obj = {
                coin_name: info[0].coin_code,
                data_info: data[i]
            };

            resolve(obj);
        });
    }));
}

// wait till all coin requests will be finished
Promise.all(promiseList).then(function(results) {
    console.log(results);
});

Pay attention to if (err) reject(err), resolve(obj) and Promise.all. It could be very tricky for you =/ Also, in cases when data.length is really huge (>100 elements), you'll make >100 requests to your DB immediately, it's not so cool =( May be you'll need to organize queue of requests.

Here is documentation for Promise.all API https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

steppefox
  • 1,784
  • 2
  • 14
  • 19
1

this is happened due to your loop execute very fast and your coin_model.find(query, function (err, info) { not result in that time

you can do here like this here is the link to doc async

// Import async module
  async = require('async');      

  async.eachOfSeries(data,
    // Each item in array you can get here
    function (item, index, cb) {

      var query = { '_id': mongoose.Types.ObjectId(item.coin_id) };

      var coin_data = coin_model.find(query, function (err, info) {

        if (err) {
          return cb(err)
        } else {
          if(Array.isArray(info) && info.length > 0){
            var a = {}
          a['coin_name'] = info[index].coin_code;
          a['data_info'] = data[index];
          var myJsonString = JSON.stringify(a);
          data_info1 += JSON.parse(myJsonString);
           cb()
          } else {
            cb('No result found in database')
          }
        }

      });

    },
    //this is the final callback
    function (err, result) {

      //ii final callback here 
    })
Manjeet Thakur
  • 2,288
  • 1
  • 16
  • 35