猫鼬按升序排序

mongoose sorting by ascending order

const followingUsers = await User.find({ _id: { $in: foundUser.followings } })
const getFeedData = async() => {
    let data = []
    for (let user of followingUsers) {
        const userPosts = user.posts
        for (let post of userPosts) {
            const posts = await Post.find({ _id: post })
            for (let post of posts) {
                const foundPost = await Post.findById(post._id).sort({ createdAt: -1 })
                data.push(foundPost)
            }
        }
    }
    return data
}
const posts = await getFeedData()

这是一些示例数据,假设有两个相同的用户 我想获取他们的帖子并按升序对它们进行排序,那些 两个用户是我关注的用户,我需要获取他们所有的帖子 并在动态消息中显示它们

   "user": [
    {
      _id: ObjectId("625c053cfdd023e3713b297f"),
      email: "user1@yahoo.com",
      isAdmin: false,
      chats: [],
      blockedChats: [],
      feedback: [],
      plans: [],
      posts: [
        ObjectId("625c0577fdd023e3713b29c7"),
        ObjectId("625c0582fdd023e3713b29f5"),
        ObjectId("625c075f8f794ea1fcf6c6af"),
        ObjectId("625c4a742db74795a43d5243")
      ],
      opportunities: [],
      username: "sam",
      createdAt: ISODate("2022-04-17T12:17:01.095Z"),
      updatedAt: ISODate("2022-04-17T17:12:20.341Z"),
      __v: 4
    }
  ],
  "post": [
    {
      _id: ObjectId("625c0577fdd023e3713b29c7"),
      postText: "hi this is sam\r\n",
      likes: [],
      likesCount: [],
      timePosted: ISODate("2022-04-17T12:09:05.535Z"),
      postImage: [],
      user: ObjectId("625c053cfdd023e3713b297f"),
      createdAt: ISODate("2022-04-01T00:00:00.00Z")
    },
    {
      _id: ObjectId("625c075f8f794ea1fcf6c6af"),
      postText: "it works !!!",
      likes: [],
      likesCount: [],
      timePosted: ISODate("2022-04-17T12:20:08.794Z"),
      postImage: [],
      user: ObjectId("625c053cfdd023e3713b297f"),
      createdAt: ISODate("2022-04-17T12:26:07.075Z"),
      updatedAt: ISODate("2022-04-17T12:26:07.075Z")
    }
  ]

Mongo playground

一切正常,除了我正在检索的文档不是按升序排列,也可能是由于循环,或者对数据库执行尽可能少的查询,这是什么问题有人可以帮忙吗?

您可能可以通过 $lookup 实现相同的逻辑。

const getFeedData = async() => {
    const foundPost = await User.aggregate([
        {
          $match: {
            _id: {
              $in: foundUser.followings
            }
          }
        },
        {
          "$lookup": {
            "from": "post",
            "let": {
              posts: "$posts"
            },
            "pipeline": [
              {
                $match: {
                  $expr: {
                    "$in": [
                      "$_id",
                      "$$posts"
                    ]
                  }
                }
              },
              {
                "$sort": {
                  createdAt: -1
                }
              }
            ],
            "as": "postLookup"
          }
        },
        {
          "$unwind": "$postLookup"
        },
        {
          "$replaceRoot": {
            "newRoot": "$postLookup"
          }
        }
      ])
    return foundPost
}
const posts = await getFeedData()

这里是Mongo playground供您参考。