Search code examples
javascriptnode.jsmongodbreturnhoisting

Hoisting / Returning variable in Javascript


I have the following code to query a MongoDB database:

   var docs;

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  findDocuments(db, function() {
    console.log(docs);
    client.close();
  });
});

const findDocuments = function(db, callback) {
    // Get the documents collection
    const collection = db.collection('oee');
    // Find some documents
    collection.find(query).toArray(function(err, docs) {
      assert.equal(err, null);
      console.log("Found the following records");
      //console.log(docs);
      callback(docs);
      return docs;   
    });
  };
}

Which outputs:

Connected successfully to server
Found the following records
undefined

I want to use the results of the query which are stored inthe variable docs for further processing. However they don´t get returned from the function. i.e. the the expression

   findDocuments(db, function() {
    console.log(docs);
    client.close();
  });

I get an "undefined" returned. What am I doing wrong?


Solution

  • You need to update the findDocuments function call as follows,

    findDocuments(db, function(docs) {
         console.log(docs);
         client.close();
    });
    

    You don't need the docs variable at the top. Use local variables as follows,

    const findDocuments = function(db, callback) {
         // Get the documents collection
         const collection = db.collection('oee');
         // Find some documents
         collection.find(query).toArray(function(err, docs) {
             assert.equal(err, null);
             console.log("Found the following records");
             return callback(docs);   
         });
     }
    

    Also note that I removed the return docs statement, as it doesn't have any importance along with the callback.

    Finally, I suggest you to learn more about callbacks (and preferably promises)