简体   繁体   中英

mongoose sort by date, multiple queries

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');
  }
};

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM