首页 > 解决方案 > 使用 Cloud Functions 时出现“TypeError:无法读取未定义的属性‘替换’”

问题描述

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

我正在关注这个文档,它在页面顶部有一个 Youtube 教程

这是我的代码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)

在此处输入图像描述

我很确定是正确的我的数据库结构如下所示:

在此处输入图像描述

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

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

为道格编辑:

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

在此处输入图像描述

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


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

标签: typescriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


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

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

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

推荐阅读