Search code examples
mongodbgomgo

The most improved way to get all likes for each post in MGO?


Likes have different collection, so do Posts.

But, maybe it is more efficient and green that:

  1. just getting all posts and when users hover on posts fetching likes
  2. or when intersection api is triggered visible on the screen, fetching likes,

Should I use lookup or aggregate or simply findall method from mongodb?

todoCollection := config.MI.DB.Collection("productpost")

pipeline := mongo.Pipeline{
        {
            {"$lookup", bson.D{
                {"from", "productfavorite"},
                {"let", bson.D{
                    {"constituents", "$productstate"}},
                },
                {"pipeline", bson.A{bson.D{
                    {"$match", bson.D{{"productstate", "Published"}}},
                }}},
                {"as", "productfavorite"},
            }},
        },
    }

cursor, err := todoCollection.Aggregate(c.Context(), pipeline)

    if err != nil {
        return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
            "success": false,
            "message": "Something went wrong",
            "error":   err.Error(),
        })
    }

    

Solution

  • I think one way of doing it will be to have a both posts and likes in same collection. Like below.

    posts : [{ id : 1, text : "this is text in post", likes : 3, likedBy : [ariana, justin, ..] }] Now, while fetching posts you can use project to not fetch likedBy list. In that way you can show users number of likes per post on first glance. And then if needed you can fetch likedBy array afterwards.