Skip to content

Instantly share code, notes, and snippets.

@d-adamkiewicz
Created April 29, 2012 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-adamkiewicz/2546626 to your computer and use it in GitHub Desktop.
Save d-adamkiewicz/2546626 to your computer and use it in GitHub Desktop.
Using async/forEachSeries() to collect data from several mongodb collections and then call callback on it
var async = require('async');
var mongo = require('mongodb');
var Db = mongo.Db,
Server = mongo.Server,
Connection = mongo.Connection;
var db = new Db('local', new Server('127.0.0.1', Connection.DEFAULT_PORT, {}));
var collections = ['names', 'fruits'];
var retData = {};
function collectIt(collName, callback) {
db.collection(collName, function(err, collection) {
collection.find().toArray(function (err, items) {
retData[collName] = items;
callback();
});
})
}
db.open(function(err, db) {
async.forEachSeries(collections, collectIt, function(err) {
db.close();
if (err) {
console.log('sorry.. an error occured');
} else {
console.dir('retData:' + JSON.stringify(retData));
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment