【问题标题】:How to get variables from other database nodes with Cloud Function .onWrite (Firebase)如何使用 Cloud Function .onWrite (Firebase) 从其他数据库节点获取变量
【发布时间】:2017-10-12 08:33:59
【问题描述】:

如果 Firebase 节点设置为 true,我正在尝试设置一些要发送的变量以传递给函数。我正在尝试使用.parent.val() 函数来设置customer_id,基于此处的文档:https://firebase.google.com/docs/functions/database-events

exports.newCloudFunction = functions.database.ref('/user/{userId}/sources/saveSource').onWrite(event => {
// Retrieve true/false value to verify whether card should be kept on file
const saveSource = event.data.val();

if (saveSource) {
  let snap = event.data;
  let customer_id = snap.ref.parent.child('customer_id').val();
  console.log(customer_id);
  // pass customer_id into function
}

我期待 snap.ref.parent 引用 /sources.child('customer_id').val() 以访问来自 customer_id 键的值。

但是,当我尝试运行此功能时,出现以下错误:

TypeError: snap.ref.parent.child(...).val is not a function
at exports.linkCardToSquareAccount.functions.database.ref.onWrite.event (/user_code/index.js:79:56)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
at process._tickDomainCallback (internal/process/next_tick.js:129:7)

如何引用原始 onWrite 位置范围之外的节点?

【问题讨论】:

    标签: javascript node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    您不能只在数据库引用上调用.val() 并期望在该位置获取数据。您需要添加一个值侦听器才能获取新数据。

    幸运的是,Cloud Functions 完全支持这一点:

    exports.newCloudFunction = functions.database.ref('/user/{userId}/sources/saveSource').onWrite(event => {
        // Retrieve true/false value to verify whether card should be kept on file
        const saveSource = event.data.val();
    
        if (saveSource) {
            const customerIdRef = event.data.adminRef.parent.child('customer_id')
            // attach a 'once' value listener to get the data at this location only once
            // this returns a promise, so we know the function won't terminate before we have retrieved the customer_id
            return customerIdRef.once('value').then(snap => {
                const customer_id = snap.val();
                console.log(customer_id);
                // use customer_id here
            });
        } 
    });
    

    您可以了解更多here

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多