Firestore Cloud Function 空集合 [英] Firestore Cloud Function empty collection

查看:26
本文介绍了Firestore Cloud Function 空集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题困扰了我好几天.我正在尝试创建一个从 Firestore 数据库读取的 Firebase Cloud 函数.

I have a problem that's bugging me for days. I am trying to create a Firebase Cloud function that reads from the Firestore database.

我的 Firestore 数据库如下所示:

My Firestore DB looks like this:

问题是我无法像这样列出 users:

Problem is that I cannot list users like this:

db.collection('users').get().then((snapshot) => snapshot.forEach(...));

如果我尝试这样做,我会得到空响应,就像我的 users 集合中没有用户一样.

If I try to do this I get empty response, like there are no users in my users collection.

但我尝试直接访问用户它有效:

But I try to access user directly it works:

await db.collection('users/5CZxgu8nmNXu2TgplwOUdOIt8e33/receipts').get()

我的完整代码:

import * as functions from 'firebase-functions';

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.cat = functions.https.onRequest(async (req, res) => {
    const receiptList: any = [];
    const db: Firestore = admin.firestore();

    const usersRef = await db.collection('users').get();
    console.log(usersRef.empty);        // Returns true

    const receiptsRef = await db
        .collection('users/5CZxgu8nmNXu2TgplwOUdOIt8e33/receipts')
        .get();

    receiptsRef.forEach((receipt: any) => {
        console.log(receipt);
        receiptList.push(receipt);
        // Here I can access data
    });

    res.send(receiptList);
    return '';
});

有人知道我做错了什么吗?谢谢!

Does anyone have any idea what I'm doing wrong? Thank you!

推荐答案

您的 users 集合实际上是空的.看看文档 ID 是如何以斜体显示的?这意味着实际上并没有一个文档在它的位置,但是,有一些子集合,在它们下面组织了文档.

Your users collection is actually empty. See how the document IDs are shown in italics? That means there is not actually a document in its place, however, there are subcollections with documents organized underneath them.

当您查询一个集合时,您只会获取该集合中的文档.查询不会获取子集合中组织的文档.在这方面,查询被称为浅层".如您所见,您需要更深入地了解子集合以获取其文档.

When you query a collection, you only get the documents that are immediately within that collection. A query will not pick up documents organized in subcollections. In this respect, queries are said to be "shallow". As you've seen, you need to reach deeper into the subcollection to get its documents.

最重要的是,您所显示的查询正在做他们应该做的事情.

Bottom line is that the queries you're showing are doing exactly what they're supposed to do.

这篇关于Firestore Cloud Function 空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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