【问题标题】:Firestore - How to get the doc id from FirebaseFirestore.QuerySnapshot?Firestore - 如何从 FirebaseFirestore.QuerySnapshot 获取文档 ID?
【发布时间】:2019-03-22 11:07:00
【问题描述】:

我正在查询特定文档的集合,并尝试从 FirebaseFirestore.QuerySnapshot 类型的查询结果中获取文档 ID。

我的实际查询如下所示(我使用的是 async/await):

result = await db.collection("chatrooms").where("userA", "==", req.body.userA)
            .where("userB", "==", req.body.userB).limit(1).get();

我试过了:

await result.docs.map(doc => {
            return doc.id
        })

但这给了我一个undefined 回复。

我做错了什么?

【问题讨论】:

    标签: typescript firebase google-cloud-firestore


    【解决方案1】:

    QuerySnapshot 包含零个或多个表示查询结果的 DocumentSnapshot 对象。文档可以通过 docs 属性作为数组访问,也可以使用 forEach 方法进行枚举。文档的数量可以通过 empty 和 size 属性来确定。

    所以它将返回一个QueryDocumentSnapshots 的数组(QuerySnapshot)。您需要使用forEach() 遍历快照,然后您可以从每个QueryDocumentSnapshot 获取文档ID

    https://firebase.google.com/docs/reference/js/firebase.firestore.QueryDocumentSnapshot

    如果您使用的是 typescript,您应该能够在 IDE 中看到定义、方法和属性。

    【讨论】:

    • 在 VSCode 中,即使用 JS 编写,如果您将鼠标悬停在 Firebase 代码上,您仍然可以看到 TS 定义。
    • 我在我的代码中使用了 forEach() 但仍然没有定义。如何从异步中获取值返回并将其用于需要在异步之后运行的另一个函数?
    猜你喜欢
    • 2018-09-03
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2020-12-05
    • 2019-07-04
    • 2019-05-05
    • 2021-11-14
    相关资源
    最近更新 更多