我有一个名为“类(class)”的集合,其中有一个名为“学生”的子集合。我想获得学生子集合数量最多的五个类(class)集合。 我的代码:
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)));
所以我的查询应该遍历所有类(class)并计算学生子集合,以获得五个类(class)集合以及更多学生子集合
最佳答案
没有内置方法可以根据 students
子集合中的属性过滤 courses
集合中的文档。 Firestore 中的查询只能筛选从中返回文档的集合的属性。
因此,为了允许查询类(class)的学生人数,您必须向每个类(class)文档添加一个 studentCount
字段。每当您添加/删除学生时,您都可以使用 FieldValue.increment()
函数从代码中更新此字段。
完成后,您将能够通过过滤您创建的字段来获取学生人数最多的类(class),类似于您已有的代码。
关于javascript - firestore 获取五个具有更多子集合数量的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023522/