【问题标题】:Firebase Functions Database 'child_added' Only Returning 1st Child (out of many children)Firebase 函数数据库“child_added”仅返回第一个孩子(在许多孩子中)
【发布时间】:2017-11-28 00:19:12
【问题描述】:

我正在想办法返回 {"length": "2","height": "4"},{"length": "1.5","height": "6"},{"length": "3","height": "5.5"},{"length": "2","height": "3.2"} 来自我的 RTDB 中的以下设置。 我忘了包括什么?

{
    "widgets": {
        "widget01": {
            "length": "2",
            "height": "4"
        },
        "widget02": {
            "length": "1.5",
            "height": "6"
        },
        "widget03": {
            "length": "3",
            "height": "5.5"
        },
        "widget04": {
            "length": "7",
            "height": "3.2"
        }
    }
}

我的功能是……

exports.widgets = functions.database.ref().onUpdate(event => {
    admin.database().ref('/widget').once('child_added', snapshot =>{
      let data = snapshot.val()
      console.log(data)
      return ({data})
    });
});

但这只是返回{"length": "2","height": "4"},而不是“widget[i]”中的每个孩子。我还以为...

...child_added 被触发一次对于每个现有的孩子...

PS。而不是child_added,我确实尝试使用value。但是我不知道如何在.child() 中引用“widget[i]”,因为它是动态的。

exports.widgets = functions.database.ref().onUpdate(event => {    
    admin.database().ref('/widgets').child(<<how to structure?>>).once('value', snapshot =>{
        let data = snapshot.val()
        console.log(data)
        return ({data})
    });
});

【问题讨论】:

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


    【解决方案1】:

    由于您正在调用once('child_added',因此您的回调只会被触发一次:对于您将侦听器附加到的位置的第一个孩子。

    如果您需要 Cloud Functions 中的所有子节点,您确实应该使用 once('value',它会立即在快照中提供所有匹配的子节点。然后,您使用snapshot.forEach() 遍历这些孩子:

    exports.widgets = functions.database.ref().onUpdate(event => {    
        admin.database().ref('/widgets').once('value', snapshot =>{
            snapshot.forEach((child) => {
                let data = child.val()
                console.log(data)
                //return ({data})
            });
        });
    });
    

    我不确定您要返回什么。既然可以有多个孩子,那你要返回哪个孩子呢?

    【讨论】:

    • 你是救生员。我一直试图弄清楚这一点比我想承认的要长。我实际上想归还所有的孩子。我根据自己的需要对其进行了更多调整,现在显示为:[ [ 2, 4 ], [ 1.5, 6 ] ]
    猜你喜欢
    • 2018-03-19
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2021-11-16
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多