javascript - firestore 获得五个具有更多子集合数量的文档
问题描述
我有一个名为课程的集合,还有一个名为学生的子集合。我想获得学生子收藏数量最多的五个课程收藏。我的代码:
await app.firestore()
.collection('courses')
.orderBy('students', 'desc')
.limit(5)
.get()
.then(query => {
let recommendedCourses = [];
query.forEach(doc => {
recommendedCourses.push({id: doc.id, ...doc.data()})
});
dispatch(setRecommendedCourses(recommendedCourses))
}).catch(error => console.log(JSON.stringify(error)));
所以我的查询应该遍历所有课程并计算学生子集合以获得五个课程集合和更多学生子集合
解决方案
没有内置方法可以根据子集合courses
中的属性过滤集合中的文档。students
Firestore 中的查询只能过滤从其返回文档的集合的属性。
因此,要允许查询课程的学生人数,您必须在studentCount
每个课程文档中添加一个字段。每当您添加/删除学生时,您都可以使用该FieldValue.increment()
功能从代码中更新此字段。
一旦你有了这个,你就可以通过过滤你创建的字段来获得最多学生的课程,类似于你已经拥有的代码。
推荐阅读
- shopify - [Shopify]如何更改搜索结果的列表顺序?
- django - 如何比较 Django 表单中的 2 个字段
- javascript - NuxtJS (Vue.js) Google Maps & Autocomplete inside v-if 一旦切换就不会显示,仅在初始页面加载时
- excel - 过滤和删除行
- php - 如何在 WordPress 中添加带有自定义后缀的新图像尺寸?
- azure - Azure DevOp-部署组-使目标 VM 联机
- excel - Excel冻结特定列
- maven - Intellij 2020.3 for maven 项目中的 Jhipster v6.10.5 javax.servlet 错误
- reactjs - 右键单击引导 OverlayTrigger?
- javascript - 当提到更高的角色时返回