从mongodb connect返回一个数组并查找

时间:2017-09-28 11:40:11

标签: javascript node.js mongodb

我有以下代码用于连接到我的MongoDB实例并返回一些recored。我需要遍历游标结果,为我的应用程序创建一个合适的数据结构。但是,我努力研究如何将表数组的内容返回给调用函数。如果我预定义一个表变量,但这不是我需要实现的,它可以工作。

如何让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()
    })
})

1 个答案:

答案 0 :(得分:2)

使用方法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();
          });
        });