The following are the contents of the file tags.js. 
//the following initializes the MongoDB library for Javascript.
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
//connection URL
abc = 'mongodb://localhost:27017/abcbase/
/* the following is a global variable
    where I want retrieved content */
var arrayToReturn = []; 
/* toFind is a dictionary, toSearch is a 
   MongoDB collection (input is its name as a string) */
function findElemHelper(toSearch, toFind) {
    /* establishes connection to the database abcbase
       and runs the contents of the function that is
       the second input */
    MongoClient.connect(abc, function(err, db) {
        /* coll is the collection being searched.
           tempCurs is the results of the search returned
           as a cursor
        */
        coll = db.collection(toSearch);
        tempCurs = coll.find(toFind);
        /* the three lines below this comment
           form the crux of my problem. I expect
           arrayToReturn to be assigned to docs
           (the contents of the cursor received by 
           the find function). Instead it seems like
           it is declaring a new variable in local scope.*/
        tempCurs.toArray(function(err, docs) {
            arrayToReturn = docs;
        }); 
    }); 
}
function findElem(toSearch, toFind) {
    findElemHelper(toSearch, toFind);
    return arrayToReturn;
}
function returnF() {
    return arrayToReturn;
}
var ln = findElem("userCollection", {});
var lm = returnF();
console.log(ln);
console.log(lm);
When I run the file using the node interpreter with the command node tags.js, it prints
[]
[]
And when I run the same code on the node interpreter (which I enter with the command node from Terminal and copy-paste the same code into the shell), console.log(ln) prints [] and console.log(lm) prints the contents of the document I want to retrieve from MongoDB.
Could someone explain this behavior?
 
     
     
    