Scenario: There are users and users has many posts. For a particular group of users, I need to fetch 10 recent posts per user and send them in response.
Here is what I have come up with:
users is array having user info.
var allPosts = [];
for(var i=0; i<users.length; i++){
(function(i){ //Level-1
db.collection('posts', function(err, postCollection){
(function(i){ //Level-2
postCollection.find({"user_id": users[i]['user_id']}).sort({"created": -1}).limit(10).toArray(function(err, post) {
(function(i){ //Level-3
for(var j =0; j< post.length; j++){
(function(j){
post[j]['created'] = ObjectId(post[j]['_id'].toString()).getTimestamp();
allPosts.push(post[j]);
if(j === post.length-1){
res.send(allPosts);
}
})(j);
}
})(i);
});
})(i);
});
})(i);
}
Now, the execution order is preserved up to Level-2, but when it enters Level-3, all things just go wrong: I have two users in array and one user has 3 posts and another has 10 posts, sometimes response is only 3 posts and sometimes all the 13 posts. I think its because of MongoDB. I am even taking care of execution order by using immediately invoked function expression(IIFE), but it just does not seem to work here. Any help is appreciated. Thanks