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