【问题标题】:Firebase Documents in Collection Query are Type Undefined集合查询中的 Firebase 文档类型未定义
【发布时间】:2021-06-29 12:49:59
【问题描述】:

我的函数的目标是遍历集合“社区”中的几个“社区”文档。每个社区文档都有一个名为“posts”的文档集合,我在其中查询具有最高值“hotScore”的文档。然后我遍历这些文档(包含在postsQuerySnapArray 中)以访问其中的数据。

我的问题是,当我遍历postQuerySnapArray 时,postQuerySnap 中的每个文档的类型都是未定义的。我已经验证所有社区都包含一个“帖子”集合,并且每个帖子文档都有一个“hotScore”属性。有谁知道可能导致这种行为的原因是什么?谢谢!

exports.sendNotificationTrendingPost = functions.https.onRequest(async (req, res) => {
    try {

        const db = admin.firestore();
        const communitiesQuerySnap = await db.collection('communities').get();

        const communityPromises = [];

        communitiesQuerySnap.forEach((community) => {
            let communityID = community.get('communityID');
            communityPromises.push(db.collection('communities').doc(communityID).collection('posts').orderBy('hotScore', 'desc').limit(1).get())
        });

        const postsQuerySnapArray = await Promise.all(communityPromises);

        postsQuerySnapArray.forEach((postsQuerySnap, index) => {

            const hottestPost = postsQuerySnap[0]; //postsQuerySnap[0] is undefined!
            const postID = hottestPost.get('postID'); //Thus, an error is thrown when I call get on hottestPost
            //function continues...

【问题讨论】:

  • 如果您从网页(或您的应用程序的屏幕)执行db.collection('communities').doc(communityID).collection('posts').orderBy('hotScore', 'desc').limit(1).get() 并且正确值为communityID,您能否确认您得到了结果。换句话说,您能否在 Cloud Function 之外验证此查询是否正常工作。
  • 另外,您确定对于第一个查询的每个结果,community.get('communityID') 不是未定义的吗?
  • 是的,我刚刚确认查询在我的 iOS 应用程序中运行时可以正常工作。我在上面编写了我的 Firebase 云功能的确切功能(从每个社区查询最热门的帖子),它按预期工作。我还验证了community.get('communityID') 在我的云函数中从未未定义。
  • 当我在没有按“hotScore”排序或没有限制的情况下进行查询时,我也会得到相同的行为

标签: node.js firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

终于弄清楚我的问题是什么。而不是通过调用获取postsQuerySnap中的元素

const hottestPost = postsQuerySnap[0];

我更改了代码以通过在 postsQuerySnap 上使用 forEach 来获取元素

var hottestPost;
postsQuerySnap.forEach((post) => {
    hottestPost = post;
})

我仍然不太清楚为什么postsQuerySnap[0] 最初不起作用,所以如果有人知道,请发表评论!

编辑:正如 Renaud 在他的评论中所说,更好的解决方法是 const hottestPost = postsQuerySnap.docs[0],因为 postsQuerySnap 不是数组。

【讨论】:

  • 正如comment to the other answer 中提到的那样,我现在才意识到它实际上是由我的答案中的错误引起的......应该是const hottestPost = postsQuerySnap.docs[0]; 而不是const hottestPost = postsQuerySnap[0];。跨度>
猜你喜欢
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多