Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. getPostsFromUserSpaghetti: function(req, res){
  2.  
  3. //get the username from a url parameter
  4. var userName = req.param('username');
  5.  
  6. //try to find a user with the passed name
  7. User.findOneByName(userName)
  8. //here we say that the user should already contain all posts
  9. //it's not possible to say that the posts should contain all comments
  10. //which is the problem we are trying to solve here
  11. .populate('posts')
  12. .then(function (user) {
  13. //if no user exists with that username, we return a 404 error
  14. if(!user) return res.notFound();
  15.  
  16. //get all posts from that user
  17. var posts = user.posts;
  18.  
  19. //count the posts
  20. var length = posts.length,
  21. i = 0;
  22.  
  23. //now for each post...
  24. posts.forEach(function(post){
  25. //... we are searching all comments...
  26. Comment.find({post: post.id})
  27. .then(function(comments){
  28.  
  29. //... and attach them to the post
  30. post.attachedComments = comments;
  31.  
  32. //here we increment our post-counter...
  33. i++;
  34. //and when every post is dealt with we can return the response
  35. if( i == length ){
  36. return res.json(user);
  37. }
  38. })
  39. .fail(function(error){
  40. sails.log.error(error);
  41. return res.negotiate(error);
  42. });
  43. });
  44.  
  45. })
  46. .fail(function(error){
  47. sails.log.error(error);
  48. return res.negotiate(error);
  49. });
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement