英文:
The most improved way to get all likes for each post in MGO?
问题
Likes
有不同的集合,Posts
也是如此。
但是,也许更高效和环保的做法是:
- 只获取所有的
posts
,当用户悬停在帖子上时再获取likes
。 - 或者当触发交集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:
- just getting all
posts
and when users hover on posts fetching likes - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论