首页 > 解决方案 > 类型错误:无法读取未定义的属性“文本”

问题描述

我遵循道格史蒂文森展示的完全相同的程序。仍然不知道为什么我会收到此错误。我对云功能完全陌生。我收到此错误:

    onMessageCreate
    TypeError: Cannot read property 'replace' of undefined 
               at addPizzazz (/srv/lib/index.js:16:17) 
               at exports.onMessageCreate.functions.database.ref.onCreate (/srv/lib/index.js:12:18) 
               at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23) 
               at /worker/worker.js:825:24 at <anonymous> 
               at process._tickDomainCallback (internal/process/next_tick.js:229:7)

我的 index.ts 文件是

import * as functions from 'firebase-functions'

export const onMessageCreate = functions.database
.ref('/rooms/{roomId}/messages/{messageId}')
.onCreate((snapshot, context) => {
    console.log(`triggered onCreate`)
    const roomId = context.params.roomId
    const messageId = context.params.messageId
    console.log(`New Message ${messageId} in room ${roomId}`)

    const messageData = snapshot.val()
    const text = addPizzazz(messageData.text) 
    return snapshot.ref.update({ text: text })
}) 

function addPizzazz ( text: string):string{
    return text.replace(/\bpizza\b/g,'')
}

我的数据库看起来像这样。

我项目的数据库

为了像 doug 一样创建我的数据库,我在我的应用程序中使用了这段代码。

String s1 = myRef.push().getKey();
        myRef.child("rooms").child("pizzachat").child("messages").child(s1).child("text").setValue("What the hack is that?!");
        myRef.child("rooms").child("pizzachat").child("messages").child(s1).child("name").setValue("Fear");

        String s2 = myRef.push().getKey();
        myRef.child("rooms").child("pizzachat").child("messages").child(s2).child("text").setValue("Who puts broccoli in pizza?!");
        myRef.child("rooms").child("pizzachat").child("messages").child(s2).child("name").setValue("Joy");

        String s3 = myRef.push().getKey();
        myRef.child("rooms").child("pizzachat").child("messages").child(s3).child("text").setValue("That's it. I'm done.");
        myRef.child("rooms").child("pizzachat").child("messages").child(s3).child("name").setValue("Disgust");

        String s4 = myRef.push().getKey();
        myRef.child("rooms").child("pizzachat").child("messages").child(s4).child("text").setValue("Congratulations pizza");
        myRef.child("rooms").child("pizzachat").child("messages").child(s4).child("name").setValue("Anger");

我根本不了解 Android 和 Firebase。我试图寻求帮助,但没有得到帮助。我开始只学习那些能帮助我实现我的想法的模块。

我怎样才能解决这个问题?

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

解决方案


您可能在编写子name节点之前编写节点text。如果你这样做,那么传递给 onCreate 的快照将只包含name而不包含text. 您将需要同时提交两个子节点,以便在创建消息节点时 onCreate 将拾取它们。请务必完全按照视频中的说明进行操作。


推荐阅读