集合查询中的Firebase文档类型未定义 [英] Firebase Documents in Collection Query are Type Undefined

查看:27
本文介绍了集合查询中的Firebase文档类型未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的职责是在社区"集合中循环浏览多个社区"文档.每个社区文档都有一个称为"posts"的文档集合,在该文档中,我以"hotScore"的最大值查询该文档.然后,我遍历这些文档(包含在 postsQuerySnapArray 中)以访问其中的数据.

The goal of my function is to loop through several 'community' documents in the collection 'communities'. Each community document has a collection of documents called 'posts' where I query the document with the highest value of 'hotScore'. I then loop through those documents (contained in postsQuerySnapArray) to access the data in them.

我的问题是,当我遍历 postQuerySnapArray 时, postQuerySnap 中的每个文档都是未定义的类型.我已验证所有社区都包含帖子"集合,并且每个帖子文档都具有"hotScore"属性.有谁知道是什么原因导致这种现象?谢谢!

My issue is that when I loop through the postQuerySnapArray, every document in postQuerySnap is of type undefined. I have verified that all communities contain a 'posts' collection and every post document has a 'hotScore' property. Does anyone know what could be causing this behavior? Thanks!

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...

推荐答案

最后弄清楚了我的问题所在.而不是通过调用

Finally figured out what my problem was. Instead of getting the element in postsQuerySnap by calling

const hottestPost = postsQuerySnap[0];

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

I changed my code to get the element by using a forEach on postsQuerySnap

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

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

I'm still not quite sure why postsQuerySnap[0] didn't work originally, so if anyone knows please leave a comment!

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

As Renaud said in his comment, a better fix would be const hottestPost = postsQuerySnap.docs[0] since postsQuerySnap is not an array.

这篇关于集合查询中的Firebase文档类型未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆