You can use async library in nodejs https://github.com/caolan/async. This helps to execute group of functions in series or parallel and once all those are completed a final callback is invoked where you can do your rendering part.
Edit by question author:
This was an excellent suggestion and worked beautifully! Here's how:
db.collection('blogPosts').getPage(req.param('page') || 1, 3, function (err, blogPosts) {
if (err) req.next(err);
var addUsersArray = [];
blogPosts.forEach(function (blogPost) {
addUsersArray.push(function (callback) {
db.collection('users').findOne({ _id: blogPost.author }, function (err, user) {
if (err) callback(err);
blogPost.author = user;
callback(null, blogPost);
});
});
});
async.parallel(addUsersArray, function (err, blogPosts) {
if (err) req.next(err);
var viewModel = {
posts: blogPosts
};
res.renderView('blog/index', viewModel);
});
});
the following also works well
db.collection('blogPosts').getPageOfPosts(req.param('page') || 1, 3, function (err, blogPosts) {
if (err) req.next(err);
async.each(blogPosts,function (blogPost,cb) {
db.collection('users').findOne({ _id: blogPost.authorId }, function (err, user) {
if (err) req.next(err);
blogPost.author = user;
cb(err);
});
},function(error)
{
var viewModel = {
posts: blogPosts
};
res.render('blog/index', viewModel);
});
});