集合查询中的Firebase文档类型未定义



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

我的问题是,当我循环遍历postQuerySnapArray时,postQuerySnap中的每个文档的类型都是未定义的。我已经验证了所有社区都包含一个"posts"集合,并且每个post文档都有一个"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...

终于发现了我的问题所在。而不是通过调用来获取postsQuerySnap中的元素

const hottestPost = postsQuerySnap[0];

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

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

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

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

最新更新