I have the following code that I use to connect to my MongoDB instance and return some recored. I need to iterate over the cursor results to create a suitable data structure for my application. However, I struggling to work out how to return the contents of the table array to the calling function. It works if I predefine a table variable but that is not what I need to achieve.
How can I get the findUsage function to return the table array to the callingMongoClient.connect code?
const MongoClient = require('mongodb').MongoClient
const assert = require('assert')
const url = 'mongodb://localhost:27017/test'
const table = []
const findUsage = function (db, callback) {
const cursor = db.collection('usage')
.find({ },
{'customer': 1})
cursor.each(function (err, doc) {
assert.equal(err, null)
if (doc != null) {
table.push(
[doc.customer]
)
} else {
callback(table)
}
})
}
MongoClient.connect(url, function (err, db) {
assert.equal(null, err)
findUsage(db, function () {
// console.log("Session: %j", table);
console.log(table)
db.close()
})
})