猫鼬按日期排序,多个查询

哈里·扬(Harry Young):

我的网站上有一个“关注”部分,它检索该用户关注的所有用户的帖子。有没有办法让这些按日期排序?

这是到目前为止的代码:

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');
  }
};
Cuong Le Ngoc:

您可以使用$ in在一个查询中找到关注的用户的所有帖子,然后对该查询进行排序。例:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章