Node.js 集合查询中的Firebase文档类型未定义
我的功能的目标是循环浏览集合“communities”中的几个“community”文档。每个社区文档都有一个名为“posts”的文档集合,我在其中查询具有最高值“hotScore”的文档。然后我循环浏览这些文档(包含在Node.js 集合查询中的Firebase文档类型未定义,node.js,firebase,google-cloud-firestore,google-cloud-functions,Node.js,Firebase,Google Cloud Firestore,Google Cloud Functions,我的功能的目标是循环浏览集合“communities”中的几个“community”文档。每个社区文档都有一个名为“posts”的文档集合,我在其中查询具有最高值“hotScore”的文档。然后我循环浏览这些文档(包含在postsQuerySnapArray中),以访问其中的数据 我的问题是,当我在postQuerySnapArray中循环时,postQuerySnap中的每个文档都是未定义的类型。我已经验证了所有社区都包含一个“posts”集合,并且每个post文档都有一个“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...
终于明白我的问题是什么了。而不是通过调用
const hottestPost = postsQuerySnap[0];
我通过在postsQuerySnap上使用forEach来更改代码以获取元素
var hottestPost;
postsQuerySnap.forEach((post) => {
hottestPost = post;
})
我仍然不太清楚为什么postsQuerySnap[0]
最初不起作用,所以如果有人知道,请留下评论
编辑:正如雷诺在他的评论中所说,更好的解决方法是
const hottestPost=postsQuerySnap.docs[0]
,因为postsQuerySnap不是数组。如果你从网页上执行db.collection('communities').doc(communityID.).collection('posts').orderBy('hotScore','desc').limit(1).get()
,你能确认得到一个结果吗(或应用程序的屏幕)的正确值为communityID
。换句话说,您能否在云功能之外验证此查询是否正常工作。此外,您是否确定,对于第一次查询的每个结果,community.get('communityID')
不是未定义的?是的,我刚刚确认在我的iOS应用程序中运行时查询工作正常。我编程了上面我的Firebase cloud函数的确切功能(从每个社区查询hottestPost),它按预期工作。我还验证了community.get('communityID')
在我的云函数中从来都是未定义的。当我不按“hotScore”排序或没有限制进行查询时,我也会得到相同的行为。正如a中提到的,我刚刚意识到这实际上是由我的答案中的错误引起的……应该是const hottestPost=postsQuerySnap.docs[0];
而不是常量hottestPost=postsQuerySnap[0];
。