You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore中无法获取Top3平均评分书籍ID的问题求助

Firestore中无法获取Top3平均评分书籍ID的问题求助

兄弟,我看了你的Firestore数据结构和代码,知道为啥拿不到数据了!

你现在的fetchTopRatedBookIds函数只获取了rating_book集合里的文档,但这些文档其实只是书籍ID对应的父文档,真正的评分数据都在每个父文档下的ratings子集合里呢!你现在的代码没去读取这些子集合的内容,自然拿不到评分数据来计算平均评分。

先给你理清楚你的数据结构:

  • 顶层集合:rating_book,每个文档的ID就是书籍的bk_ID
  • 每个书籍文档下的子集合:ratings,里面的每一条文档就是用户给这本书的评分记录

那修正后的代码应该是这样的,要遍历每个书籍文档,然后去读取它的ratings子集合,计算每本书的平均评分,最后再排序取Top3:

const fetchTopRatedBookIds = async() => {
  try {
    const booksSnapshot = await getDocs(collection(db, 'rating_book'));
    const bookAverageRatings: { bookId: string; average: number }[] = [];

    await Promise.all(booksSnapshot.docs.map(async (bookDoc) => {
      // 获取当前书籍的ratings子集合
      const ratingsSnapshot = await getDocs(collection(bookDoc.ref, 'ratings'));
      
      if (ratingsSnapshot.empty) return; // 如果没有评分就跳过

      // 计算所有评分的总和
      const totalRating = ratingsSnapshot.docs.reduce((sum, ratingDoc) => {
        return sum + (ratingDoc.data().rating as number);
      }, 0);

      // 计算平均分
      const averageRating = totalRating / ratingsSnapshot.size;
      
      bookAverageRatings.push({
        bookId: bookDoc.id, // 这里bookDoc.id就是书籍的bk_ID
        average: averageRating
      });
    }));

    // 按平均分从高到低排序,取Top3
    const topRatedBooks = bookAverageRatings.sort((a, b) => b.average - a.average).slice(0, 3);
    
    console.log("Top3评分书籍:", topRatedBooks);
    return topRatedBooks;
  } catch (error) {
    console.error("获取评分数据失败:", error);
    throw error;
  }
};

另外还要提醒你几个点:

  • 确保你的Firestore安全规则允许读取rating_book集合和它下面的ratings子集合,不然会因为权限问题拿不到数据
  • 如果你的书籍数量很多,这种嵌套读取的方式可能会有性能问题,后期可以考虑预计算平均分(比如在rating_book的书籍文档里直接存averageRating和ratingCount字段,每次新增评分时更新这两个值),这样查询的时候直接读顶层文档就能拿到平均分,效率高很多

备注:内容来源于stack exchange,提问作者Rida Fatima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 08:48:09