首页 > 解决方案 > 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)));

所以我的查询应该遍历所有课程并计算学生子集合以获得五个课程集合和更多学生子集合

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


没有内置方法可以根据子集合courses中的属性过滤集合中的文档。studentsFirestore 中的查询只能过滤从其返回文档的集合的属性。

因此,要允许查询课程的学生人数,您必须在studentCount每个课程文档中添加一个字段。每当您添加/删除学生时,您都可以使用该FieldValue.increment()功能从代码中更新此字段。

一旦你有了这个,你就可以通过过滤你创建的字段来获得最多学生的课程,类似于你已经拥有的代码。


推荐阅读