首页 文章

如何使用Cloud Function .onWrite(Firebase)从其他数据库节点获取变量

提问于
浏览
0

我试图设置一些变量,如果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位置范围之外的节点?

1 回答

  • 3

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

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

    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 .

相关问题