This is an example of what I am trying to do, retrieve all the post inside a mongo db, for each of the post populate the author then use author object to retrieve the profile picture from Cloudinary.
What is the correct way to go about doing this? I've tried numerous ways of populating arrays and sending those in the response but because of the async call they are never run before the res is sent.
router.get('/posts',auth, function(req, res, next) { //var id = req.payload._id; Post.find(function(err, posts){ if(err){ return next(err); } posts.forEach(function(post){ post.populate('author',function(err,post){ post.image = cloudinary.image("v"+post.author.avatarVersion+"/profile/"+post.author._id,{ width:100, height:100,crop:'thumb',gravity:'face',radius:'max' }) //here the post object is updated console.log(post) }) }) //res.json(some posts array); }); }); Solution thanks to Dan Moldovan!
router.get('/posts',auth, function(req, res, next) { var id = req.payload._id; Post.find({}).populate('author').exec(function(err,posts){ if(err){ return next(err); } var updatedPosts = []; posts.forEach(function(post){ post.image = cloudinary.image("v"+post.author.avatarVersion+"/profile/"+post.author._id,{ width:100, height:100,crop:'thumb',gravity:'face',radius:'max' }) updatedPosts.push(post); }) res.json(updatedPosts); })