I'm trying to populate an array of posts with various mongoDB documents.
app.get('/dash/:id', isLoggedIn, (req, res) => {
var posts = [];
User.findById(req.params.id, (err, user) => {
user.follows.forEach((followId) => {
User.findById(followId, (err, follow) => {
follow.posts.forEach((postId) => {
Post.findById(postId, (err, post) => {
posts.push(post);
})
})
})
})
})
console.log(posts)
})
My problem is that the final console.log produces an empty array, but if I call console.log(posts) immediately after pushing each document into the array, everything is working fine. I'm sure there's something stupid that I'm missing. Is it running my console.log before it completes the data lookup? Thanks in advance!