I am trying to get posts from database by using ID.So I am looping around an array of Id's and using mongoose method 'findById' to get response.But the loop finishes iterations before completing the body. How to deal with this?
function getSortedPosts(callback){
var landingPosts = new Object;
categoryModel.find((err,categories) => {
if(err) console.log(err);
else{
categories.forEach((category,i) => {
landingPosts[category.category] = new Array;
//for each post in a category
category.posts.forEach((postid,j) => {
console.log(":")
//limiting posts per category to 3
if (j<3){
postModel.findById(postid,(err,foundpost) => {
if(err) console.log(err)
else{
landingPosts[category.category].push(foundpost);
if(i === categories.length-1){
console.log(i)
if(j === 2){
callback(landingPosts);
}
}
}
})
}
})
})
}
})
}
getSortedPosts((lp) => {.......})
I don't know how to use promises or async await...so I am using callbacks. Would learning them now help me with this? (I plan to learn them after present project as I am beginner and they confuse me)