【问题标题】:Cloud Function Cannot Read Property of Undefined云函数无法读取未定义的属性
【发布时间】:2020-09-01 04:28:35
【问题描述】:

Cloud Functions 新手,并试图从日志中了解我的错误。它说无法读取未定义的属性“uid”。我正在尝试将用户匹配在一起。 onCreate 将调用匹配函数来检查用户是否存在于 live-Channels 下,如果存在则将 live-Users 中两个用户下的频道值设置为 uid+uid2。日志是否还说明错误来自哪一行?很困惑它在哪里显示。

const functions = require('firebase-functions');

//every time user added to liveLooking node
exports.command = functions.database
        .ref('/liveLooking/{uid}')
        .onCreate(event => {
    const uid = event.params.uid
    console.log(`${uid} this is the uid`)
        
    const root = event.data.adminRef.root
    //match with another user
    let pr_cmd = match(root, uid)

    const pr_remove = event.data.adminRef.remove()
    return Promise.all([pr_cmd, pr_remove])
})

function match(root, uid) {
    let m1uid, m2uid
    return root.child('liveChannels').transaction((data) => {
    //if no existing channels then add user to liveChannels
    if (data === null) {
        console.log(`${uid} waiting for match`)
        return { uid: uid }
    }
    else {
        m1uid = data.uid
        m2uid = uid
        if (m1uid === m2uid) {
            console.log(`$m1uid} tried to match with self!`)
            return
        }
        //match user with liveChannel user
        else {
            console.log(`matched ${m1uid} with ${m2uid}`)
            return {}
        }
    }
},
(error, committed, snapshot) => {
    if (error) {
        throw error
    }
    else {
         return {
            committed: committed,
            snapshot: snapshot
        }
    }
},
false)
    .then(result => {
        // Add channels for each user matched
        const channel_id = m1uid+m2uid
        console.log(`starting channel ${channel_id} with m1uid: ${m1uid}, m2uid: ${m2uid}`)
        const m_state1 = root.child(`liveUsers/${m1uid}`).set({
            channel: channel_id
        })
        const m_state2 = root.child(`liveUsers/${m2uid}`).set({
            channel: channel_id
        })
        return Promise.all([m_state1, m_state2])
    })
}

【问题讨论】:

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


    【解决方案1】:

    您指的是非常旧版本的 Cloud Functions API。无论您在看什么网站或教程,它都会显示不再相关的示例。

    在现代 Cloud Functions for Firebase 中,实时数据库 onCreate 触发器接收两个参数,一个 DataSnapshot 和一个 Context。 它不再接收“事件”作为唯一参数。您将不得不将您现在使用的代码移植到新的处理方式。我强烈建议查看 product documentation 以获取现代示例。

    如果您想在尝试使用代码const uid = event.params.uid 时获取通配符参数,则必须使用文档中说明的第二个上下文参数。要从快照中访问数据,请使用第一个参数。

    【讨论】:

    • 好的。还有什么不再使用的东西吗?
    • 这是主要的。 API 多年来一直在发展。文档始终保持最新状态,因此请始终从那里开始。
    猜你喜欢
    • 2019-03-18
    • 2021-02-27
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 2018-10-30
    相关资源
    最近更新 更多