云函数无法读取未定义的属性

时间:2020-09-01 04:28:35

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

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])
    })
}

cloud functions log

1 个答案:

答案 0 :(得分:1)

您指的是Cloud Functions API的非常旧的版本。无论您要查看的是哪个网站或教程,它都显示了不再相关的示例。

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

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