2

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

1 Answer 1

2

Use the method toArray to deal with the find cursor. Then use the callback, either if there is data or not.

        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();
          });
        });
Sign up to request clarification or add additional context in comments.

1 Comment

Arh thanks. How do I get to the data in the MongoClient.connect call. e.g. console.log(??) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.