Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- getPostsFromUser: function( req, res ){
- //the beginning is pretty much the same as before
- var userName = req.param('username');
- User.findOneByName(userName)
- .populate('posts')
- .then(function (user) {
- if (!user) return res.notFound();
- var posts = user.posts,
- postIds = [];
- //we have to avoid looping over an async function
- //therefore we first have to collect all post ids...
- posts.forEach(function(post){
- postIds.push(post.id);
- });
- //... to be able to find all comments we need with just one db query
- var comments = Comment.find({post: postIds})
- .then(function(comments){
- return comments;
- });
- //with bluebird this array...
- return [user, comments];
- })
- //... will be passed here as soon as the comments are finished loading
- .spread(function(user, comments){
- //now we have our user object with all posts and an array with all the comments...
- user.posts.forEach(function(post){
- //... which means we have to attach comments to posts manually
- post.attachedComments = comments.filter(function(comment){
- return comment.post == post.id;
- });
- });
- //then we can return our user object
- return res.json(user);
- })
- .fail(function(error){
- sails.log.error(error);
- return res.negotiate(error);
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement