You need to properly handle your tree structure in an asynchronous way. Try this approach:
(I haven't tested, but hope it works)
// ...
var Forum = mongoose.model('Forum');
exports.show = function(req, res){
//Get the owner's forums
Forum.find({ ownerId: req.params.owner_id }).exec(function(err, forums) {
if(err) throw new Error(err);
if(!forums.length) return response.json(forums); //Send an empty array if no forums where found
//Build forums one by one
var forum = forums.shift();
buildForum(forum, function () {
forum = forums.shift();
if (forum) {
buildForum(forum, this);
} else {
//All forums were built.
res.json(forums);
};
});
});
var buildForum = function (forum, onSuccess) {
forum.populate('threads', function(err, forum){
if(err) throw new Error(err);
if(!forum.threads.length) return onSuccess();
//Build threads one by one
var threads = forum.threads;
var thread = threads.shift();
buildThread(thread, function () {
thread = threads.shift();
if (thread) {
buildThread(thread, this);
} else {
//All threads were built.
onSuccess();
};
});
});
};
var buildThread = function (thread, onSuccess) {
thread.populate('posts', function(err, thread){
if(err) throw new Error(err);
if(!thread.posts.length) return onSuccess();
//Build posts one by one
var posts = thread.posts;
var post = posts.shift();
buildPost(post, function () {
post = posts.shift();
if (post) {
buildPost(post, this);
} else {
//All posts were built.
onSuccess();
};
});
});
};
var buildPost = function (post, onSuccess) {
post.populate('posts', function(err, post){
if(err) throw new Error(err);
if(!post.posts.length) return onSuccess();
//Build comments one by one
var posts = post.posts;
var _post = posts.shift();
buildPost(_post, function () {
_post = posts.shift();
if (_post) {
buildPost(_post, this);
} else {
//All comments were built.
onSuccess();
};
});
});
};
};