Home > OS >  mongoose sorting by ascending order
mongoose sorting by ascending order

Time:04-19

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

Here is some sample data, imagine there are identical two users and I want to get their posts and sort them by ascending order, those two users are the users I follow and I need to get all their posts and show them on the news feed

   "user": [
    {
      _id: ObjectId("625c053cfdd023e3713b297f"),
      email: "[email protected]",
      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

everything is working okay, except the documents that I'm retrieving back are not in ascending order, it may also be due to the loops, or maybe to perform as less as possible queries to the database, what's the problem here can anyone help?

CodePudding user response:

You can probably achieving the same logic through $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()

Here is the Mongo playground for your reference.

  • Related