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?