0

I am working with node.js using express and mongoDb. I am trying to retrieve data from database "local" and collection "borrower" and pushing it into an empty array collectionOne. It is rendering this array on the view page. I want to use _id pushed in an array b_ids from this output to make a call to company_details collection under same router . The issue I am facing here is I am not getting any value in array b_ids when trying to access it under call to company_details collection.

The code is as below:

var collectionOne = [];
var collectionTwo = [];
var b_ids = [];

router.get('/fetch',function(req, res, next){
 MongoClient.connect('mongodb://localhost:27017/local', function(err, db){
    var collection = db.collection('borrower');

    db.collection("borrower", function(err, collection) {
        collection.find().toArray(function(err, result) {
                                            if (err) {
                                              throw err;
                                            } else {
                                                //console.log(result[0].first_name);
                                              for (i=0; i<result.length; i++) {
                                                collectionOne[i] = result[i];
                                                b_ids[i] = result[i]._id;
                                              }
                                            }
                                    });

        db.collection("company_details", function(err, collection){
            console.log(b_ids);
            collection.find({borrower_id : {$in :b_ids}}).toArray(function(err, result){
                if (err) {
                  throw err;
                } else {
                  for (i=0; i<result.length; i++) {
                    collectionTwo[i] = result[i];
                  }
                }
            });
        });
        res.render('index',{data : collectionOne , data1 : collectionTwo});
    }); 
 });
});

Please suggest me how can I access the b_ids array here. Thanks in advance :)

2 Answers 2

3

The callback from toArray is asynchronous, i.e. will happen after your console.log line executes, therefore you need to re-arrange as follows:

var collectionOne = [];
router.get('/fetch',function(req, res, next){
  MongoClient.connect('mongodb://localhost:27017/local', function(err, db){
    var collection = db.collection('borrower');

    db.collection("borrower", function(err, collection) {
        collection.find().toArray(function(err, result) {
            if (err) {
                throw err;
            } else {
                for (i=0; i<result.length; i++) {
                    collectionOne[i] = result[i];
                    b_ids[i] = result[i]._id;
                }

                db.collection("company_details", function(err, collection){
                console.log(b_ids);
                collection.find({borrower_id : {$in :b_ids}}).toArray(function(err, result){
                    if (err) {
                        throw err;
                    } else {
                        for (i=0; i<result.length; i++) {
                            collectionTwo[i] = result[i];
                        }
                        res.render('index',{data : collectionOne , data1 : collectionTwo});
                    }
                });
            });
        }
    });
 });
});

This ensures that the callback completes before you try and log / render it.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for reply. I know i can acces this way but what I want is to use it outside the query scope. I have modified my question to make it more clear.
@Jyoti It doesn't matter how you want to use the value returned from the callback, you have to do it within the callback. There are other ways of structuring the callbacks (e.g. using promises) but the net effect is always the same - you can't use the result before it is returned.
@Jyoti I've updated my answer, it's basically the same - you need to nest the second query in the callback from the first, if it depends on the data returned by the first query. Promises would be a better way of structuring this, but conceptually it's the same thing.
so there is no way I can access b_ids array while fetching data from company_details collection?
0

It is simple create a function with a callback function inside it as an argument

function returnBids(collection, callback){
   collection.find().toArray(function(err, result) {
      if (err) 
            throw err;
         else 
          callback(result)
     })
  }

and you can access your result outside by calling the function returnbids() .i.e

returnBids(collection,function(b_ids){
    console.log(b_ids)
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.