【问题标题】:"TypeError: Cannot read property 'replace' of undefined" when using Cloud Functions使用 Cloud Functions 时“TypeError:无法读取未定义的属性‘替换’”
【发布时间】:2019-02-16 11:21:02
【问题描述】:

我是 Cloud Functions for Firebase 的新手,我正在尝试将它们与实时数据库一起使用。

我关注this documentation where it has a Youtube tutorial at the top of the page

这是我在index.ts 中的代码:

import * as functions from 'firebase-functions';

export const onMessageCreate = functions.database
.ref('/party/{partyID}/messages/{message}')
.onCreate((snapshot, context) => {
    const messageData = snapshot.val()
    const text = addMore(messageData.text)
    return snapshot.ref.update({ text: text })
})

function addMore(text: string): string {
    return text.replace(/\bhello\b/g, 'hey')
}

但是,我的函数日志中出现以下错误:

TypeError: Cannot read property 'replace' of undefined

at addMore (/user_code/lib/index.js:12:16)
at exports.onMessageCreate.functions.database.ref.onCreate (/user_code/lib/index.js:8:18)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
at /var/tmp/worker/worker.js:733:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

我确信正确的数据库结构如下所示:

是什么导致了这个错误?是否未安装某些“包”功能?

我正在运行 node v10.9.0 和 npm 6.2.0。

为 Doug 编辑:

谢谢 Doug,这是一个很棒的视频! ???我已经编辑了我的数据库,当我添加一条消息时它现在看起来像这样(以前我的函数尝试替换单词的尝试):

我还通过在末尾添加/text 更改了TypeScript 代码参考。我还使用String()messageData 转换为一个字符串,它消除了错误并显示了您所描述的单词“未定义”。正如你所说,我已将消息与孩子分开,但我仍然对为什么我没有收到价值以及为什么它添加额外的 text 孩子感到困惑。谢谢!


如果您有任何问题,请告诉我!

【问题讨论】:

    标签: typescript firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    错误消息告诉您您向addMore 传递了一个未定义的值。然后,您尝试对该未定义的值调用字符串方法。

    您使用的参考模式与您的数据库架构不匹配。看起来您假设每条消息都作为其自己的属性存在于数据库中。这不会按您期望的方式工作,而且几乎可以肯定它不是您想要使用的数据库模型。相反,您可能应该为每条消息将新子代推送到数据库中,该数据库对于消息的文本有自己的子代。

    /party
      /{partyid}
        /messages
          /{messageid}      //  You're missing this message id in the db
            /text = "foo"
    

    【讨论】:

    • 我在我的问题中留下了更新,因为我仍然有点困惑。很高兴知道你的帮助以及制作视频:)
    【解决方案2】:

    我最终所做的是这样设置我的数据库:

    我从这样的数据库中获得了我的价值,使其成为string

    String(snapshot.child('text').val())
    

    另外,一开始,在return snapshot.ref.update({ text: text }) 中,'text' 是一个将出现在数据库中的参数。

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 2019-07-06
      • 1970-01-01
      • 2015-04-04
      相关资源
      最近更新 更多