【问题标题】:How to check a Firestore map value in TypeScript?如何在 TypeScript 中检查 Firestore 地图值?
【发布时间】:2020-09-12 21:59:29
【问题描述】:

我有一个 Firebase 云函数,它从 Firestore 中获取一个文档,并且需要从 [String: Boolean] 映射中读取一个布尔值。在以下示例中,snapshot.get("private.localNotifications") 返回该映射。而const notifyLocal = localNotifications.get("abc123") 是尝试获取硬编码键的值,但它不起作用。

admin.firestore().collection("userSettings").doc(recipientUserId).get().then((snapshot) => {
    if (snapshot.exists) {
        const notifyGlobal = snapshot.get("private.globalNotifications") || false // boolean

        if (notifyGlobal) {
            const localNotifications = snapshot.get("private.localNotifications") // [string: boolean] map
            const notifyLocal = localNotifications.get("abc123") || false // how do I check this key's value?

            if (notifyLocal) {
                ...
            }
        }
    }
}).catch((error) => {
    console.log("ERROR", error)
})

【问题讨论】:

  • 请编辑问题以显示您正在使用的实际文档数据。截图就可以了。
  • @DougStevenson 文档数据不是问题,该字段只是一个普通的[String: Bool] 地图。我通过转换字段as [string, boolean] 解决了这个问题(在下面的回答中)。虽然此解决方案有效,但这是在 TypeScript 中解压缩 Firestore 地图的首选方式吗?
  • 我了解文档数据没有问题。我建议查看实际数据将有助于可视化您实际使用的内容,以便制定有用的答案。

标签: typescript google-cloud-firestore


【解决方案1】:

Firestore 返回的映射必须转换为可识别的类型,编译器才能解析它。

admin.firestore().collection("userSettings").doc(recipientUserId).get().then((snapshot) => {
    if (snapshot.exists) {
        const notifyGlobal = snapshot.get("private.globalNotifications") || false // boolean

        if (notifyGlobal) {
            const localNotifications = snapshot.get("private.localNotifications") as [string, boolean]
            const notifyLocal = localNotifications["abc123"] || false

            if (notifyLocal) {
                ...
            }
        }
    }
}).catch((error) => {
    console.log("ERROR", error)
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2022-01-08
    • 2020-03-21
    相关资源
    最近更新 更多