【问题标题】:mongoose sort by date, multiple queries猫鼬按日期排序,多个查询
【发布时间】:2021-01-14 05:11:46
【问题描述】:

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

这是目前为止的代码:

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

【问题讨论】:

  • https://stackoverflow.com/a/31824896 回答你的问题了吗?
  • 不,因为我需要排序以包含对 x 个关注用户的所有查询...
  • 我可以分别为每个用户按日期排序,这不是问题。我正在检索 x 个用户的所有帖子,然后我需要按日期对它们进行排序

标签: javascript node.js express mongoose


【解决方案1】:

您可以使用$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();

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 2015-07-27
    • 2013-01-22
    • 2011-08-15
    相关资源
    最近更新 更多