Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. getPostsFromUser: function( req, res ){
  2.  
  3. //the beginning is pretty much the same as before
  4. var userName = req.param('username');
  5.  
  6. User.findOneByName(userName)
  7. .populate('posts')
  8. .then(function (user) {
  9. if (!user) return res.notFound();
  10.  
  11. var posts = user.posts,
  12. postIds = [];
  13.  
  14. //we have to avoid looping over an async function
  15. //therefore we first have to collect all post ids...
  16. posts.forEach(function(post){
  17. postIds.push(post.id);
  18. });
  19.  
  20. //... to be able to find all comments we need with just one db query
  21. var comments = Comment.find({post: postIds})
  22. .then(function(comments){
  23. return comments;
  24. });
  25.  
  26. //with bluebird this array...
  27. return [user, comments];
  28.  
  29. })
  30. //... will be passed here as soon as the comments are finished loading
  31. .spread(function(user, comments){
  32.  
  33. //now we have our user object with all posts and an array with all the comments...
  34. user.posts.forEach(function(post){
  35. //... which means we have to attach comments to posts manually
  36. post.attachedComments = comments.filter(function(comment){
  37. return comment.post == post.id;
  38. });
  39. });
  40.  
  41. //then we can return our user object
  42. return res.json(user);
  43.  
  44. })
  45. .fail(function(error){
  46. sails.log.error(error);
  47. return res.negotiate(error);
  48. });
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement