I have no idea what you mean by "affectation fail", but it looks like you're calling res.render
too early — callbacks are invoked asynchronously after your current context finishes executing, so when you call res.render(...)
after your for
loop has finished, your Post.find(...)...
operations still haven't finished and their callbacks haven't been invoked, so sub_posts
will be still empty.
My node.js and Mongo are rusty, so perhaps this isn't the canonical way to do it, but I'd add a counter to track the state of the pending requests and only call res.render
when all subposts have been fetched:
var sub_posts = new Array;
var pending = 0;
for (var i = 0; posts[i]; i++)
{
var tmp_path = ...
Post.find({'path': tmp_path})
.exec(function(err, bis_posts) {
if (err) console.log('Error loading subforum');
else sub_posts.push(bis_posts);
pending -= 1;
if (!pending) {
// all pending subpost lookups finished, render the response:
res.render(... 'post_list': posts, 'sub_posts': sub_posts);
}
});
pending += 1;
}