0

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?

Sebs030
  • 566
  • 2
  • 4
  • 19

2 Answers2

2

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)

Pubudu Dodangoda
  • 2,742
  • 2
  • 22
  • 38
  • thanks, very helpfull to get a better understanding of callabacks. I got confused because of the nested functions. What would be needed to make 'docs' available outside the MongoClient.connect function scope? – Sebs030 Dec 30 '17 at 12:45
  • You can use a global variable(say `var docs_global`) for that matter. Then you can assign the value of `docs` to `docs_global`. But I wouldn't recommend that practice. If you need to maintain a global state, I suggest on using the new ES6 class syntax – Pubudu Dodangoda Dec 30 '17 at 16:12
0

Change this function() { console.log(docs); client.close(); }); to this

function(docs) {
console.log(docs);
client.close();

}); because in your code you log docs variable on the top of your code which hadn't receive any value try the new code and tell me . does it work now ? I think yes .

mostafa tourad
  • 4,308
  • 1
  • 12
  • 21