Q:

Process data before express renders page

Using node and express, I'm trying to process some information before the response renders the page, but I'm not having any luck doing so. Any suggestions?
app.get("/Category", function (request, response) {
    if (request.query.Id) {
        // get all the posts by categoryId

        ForumPost.find({categoryId: request.query.Id}, function (err, posts) {
            if (err) throw err;

            var usernames = {};

            for (i = 0; i < posts.length; i++) {
                User.findById(posts[i].userId, function (err, user) {
                    if (err) throw err;
                    var username = user.username;
                    usernames[i] = username;
                });
            }
            response.render("Category", {
                message: posts,
                userList: usernames
            });

        });
    }
});

A:

You probably want to query the DB only once, using a single find with all the user ids passed in as single $in filter, and then make sure you form your response in the callback handler that mongoose wants you to pass in as second argument to the find function:
// build the list of all ids you need
var ids = posts.map(p => mongoose.Types.ObjectId(p.userId));

// let's remove duplicates, too
ids = ids.filter((id,pos) => ids.indexOf(id)===pos);

// find all these users in a single query:
User.find({
  '_id': { $in: ids}
}, (err, users) => {
  // handle the query result

  if (err) {
    // do something error related here
    return ...
  }

  // no error: get the usernames and send the response
  var usernames = users.map(user => user.username);
  response.render("Category", {
    message: posts,
    userList: usernames
  });
});

This uses modern arrow functions, but if you're on an old version of Node (pre-6) those are easily replaced with classic function signatures ((a,b,...) => c is equivalent to function(a,b,...) { return c }. Technically they're (function(a,b,...) { return c; }).bind(this) but that's not a relevant distinction in the code above).

