0

I have a 'followed' section on my website and it retrives the posts of all users the user has followed. Is there a way of getting these sorted by date?

here's the code so far:

exports.followedPosts = async (req, res) => {
  try {
    const user = await User.findById(req.user._id);
    const posts = [];

    for (const follow of user.follows) {
      const partPosts = await Post.find({ author: follow.user })
        .select('-comments')
        .populate('author')
        .exec();
      for (const post of partPosts) {
        posts.push(post);
      }
    }
    res.send(posts);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('server error');
  }
};
harry young
  • 600
  • 1
  • 8
  • 24
  • Does [https://stackoverflow.com/a/31824896](https://stackoverflow.com/a/31824896) answer your question? – Nithish Sep 28 '20 at 15:37
  • no, because I need the sort to include all of the queries for the x number of followed users... – harry young Sep 28 '20 at 15:39
  • I can sort by date for each user, separately, that isn't the problem. I am retreiving all of the posts for x number of users and then I need to sort them all by date – harry young Sep 28 '20 at 15:44

1 Answers1

2

You can find all posts of followed users in one query with $in and sort that query. Example:

let follow_users = user.follows.map(follow => follow.user);

const posts = await Post.find({ author: { $in: follow_users } })
    .select('-comments')
    .sort({date: 1})
    .populate('author')
    .exec();
Cuong Le Ngoc
  • 11,595
  • 2
  • 17
  • 39