22samuelk 22samuelk - 5 months ago 17
Node.js Question

Node.js module to fetch data from MongoDB database

I want to use an module to get and process data from my MongoDB database. (It should generate an object that represents my Express.js site's navbar)

I thought of doing something like this:

var nav = { Home: "/" };
module.exports = function() {
MongoClient.connect(process.env.MONGO_URL, function(err, db) {
assert.equal(err, null);
fetchData(db, function(articles, categories) {
combine(articles, categories, function(sitemap) {
// I got the data. What now?
console.log("NAV: ", nav);
})
});
});
};

var fetchData = function(db, callback) {
db.collection('articles').find({}).toArray(function(err, result) {
assert.equal(err);
articles = result;
db.collection('categories').find({}).toArray(function(err, result) {
assert.equal(err);
categories = result;
db.close();
callback(articles, categories);
});
});
};

var combine = function(articles, categories, callback) {
categories.forEach(function(category) {
nav[category.title] = {};
articles.forEach(function(article) {
if(article.category == category.name) {
nav[category.title][article.title] = "link";
}
})
});
callback(nav);
};


As of line 6, I do have all data I need.

(An object, currenty like
{ Home: '/', Uncategorized: { 'Hello world!': 'link' } }
)

But since I'm in an anonymous function, I don't know how to return that value. I mean,
return
would just return it the function that called it... And in the end, MongoClient.connect would receive my data.

If I set a variable instead, it would be set as
module.exports
returned before Node can even query the data from the database, right?

What can I do in order to make this work?

It should result in some kind of function, like

var nav = require('nav');
console.log(nav());


Thanks in advance!

Answer

Add another callback:

var nav = { Home: "/" };
module.exports = function(cb) {
    MongoClient.connect(process.env.MONGO_URL, function(err, db) {
        assert.equal(err, null);
        fetchData(db, function(articles, categories) {
            combine(articles, categories, function(sitemap) {
                cb(sitemap);
            })
        });
    })
});

And then use this way:

var nav = require('nav');
nav(function(sitemap){ console.log(sitemap); });