从MongoDB返回一个数组connect和find

我有以下代码,我用来连接到我的MongoDB实例,并返回一些recored。 我需要迭代游标结果来为我的应用程序创build一个合适的数据结构。 然而,我努力解决如何将表数组的内容返回给调用函数。 如果我预先定义了一个表variables,但是这不是我需要实现的。

我怎样才能得到findUsage函数返回表数组到调用MongoClient.connect代码?

 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() }) }) 

使用方法toArray来处理find cursor 。 然后使用callback ,如果有数据或者没有。

  const findUsage = function (db, callback) { const cursor = db.collection('usage') .find({}, { 'customer': 1, }); cursor.toArray(function (err, docs) { assert.equal(err, null); if (docs) { return callback(docs.map(x => x.customer)); } return callback([]); }); } MongoClient.connect(url, function (err, db) { assert.equal(null, err); findUsage(db, function (docs) { // ... db.close(); }); });