获取MGO中每篇帖子的所有点赞的最佳方法是什么?

huangapple go评论80阅读模式
英文:

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

问题

Likes有不同的集合,Posts也是如此。

但是,也许更高效和环保的做法是:

  1. 只获取所有的posts,当用户悬停在帖子上时再获取likes
  2. 或者当触发交集API时,在屏幕上可见时获取likes

我应该使用MongoDB的lookup、aggregate还是简单地使用findall方法?

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(),
    })
}
英文:

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

答案1

得分: 1

我认为一种做法是将帖子和点赞都放在同一个集合中,就像下面这样:

posts: [{
   id: 1,
   text: "这是帖子中的文本",
   likes: 3,
   likedBy: [ariana, justin, ..]
}]

现在,在获取帖子时,你可以使用投影(project)来不获取likedBy列表。这样你就可以一目了然地显示每个帖子的点赞数。然后,如果需要的话,可以随后获取likedBy数组。

英文:

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.

huangapple
  • 本文由 发表于 2021年10月28日 19:30:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/69753305.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定