Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- getPostsFromUserSpaghetti: function(req, res){
- //get the username from a url parameter
- var userName = req.param('username');
- //try to find a user with the passed name
- User.findOneByName(userName)
- //here we say that the user should already contain all posts
- //it's not possible to say that the posts should contain all comments
- //which is the problem we are trying to solve here
- .populate('posts')
- .then(function (user) {
- //if no user exists with that username, we return a 404 error
- if(!user) return res.notFound();
- //get all posts from that user
- var posts = user.posts;
- //count the posts
- var length = posts.length,
- i = 0;
- //now for each post...
- posts.forEach(function(post){
- //... we are searching all comments...
- Comment.find({post: post.id})
- .then(function(comments){
- //... and attach them to the post
- post.attachedComments = comments;
- //here we increment our post-counter...
- i++;
- //and when every post is dealt with we can return the response
- if( i == length ){
- return res.json(user);
- }
- })
- .fail(function(error){
- sails.log.error(error);
- return res.negotiate(error);
- });
- });
- })
- .fail(function(error){
- sails.log.error(error);
- return res.negotiate(error);
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement