0
 var historyQuesn = [];
    db.collection('history_QUESTIONS').find({}).toArray().then((docs)=>{
    var historyquesn = JSON.stringify(docs,undefined,2);
    var historyquesn_parse = JSON.parse(historyquesn);
    historyQuesn = historyQuesn.concat(historyquesn_parse);
},(err)=>{
    console.log(err);
});

I want to make use of the array returned by the above query in another functions. I want to make use of the documents returned by the db.find() method in some another functions using nodejs! Basically i want to use the vlaue of 'historyQuesn' in another functions. Please Help!

roh_dev
  • 275
  • 2
  • 6
  • 17

1 Answers1

0

Since the result of Your query will arrive to historyQuesn array when it's finished, so probably you call operation on data before the database query has finished. In Node.js all I/O operations are performed asynchronously thus Node goes further and execute Your code while it waits for the result of that query. Possible solution is to pass a callback function that gets executed after the database query has finished. Quick example:

function queryCollection(collection, callback) {
    collection.find({}).toArray(function(err, result) {
        if (err) {
            console.log(err);
        } else if (result.length > 0) {
            callback(result);
        }
    });
}

queryCollection(collection, function(result){
    console.log(result);
    // Proceed with Your result here
});

I recommend to read about asynchronous programming if You would like to use Node.js

KarlR
  • 1,545
  • 12
  • 28