[英]How to get variables from other database nodes with Cloud Function .onWrite (Firebase)
如果Firebase節點設置為true,我嘗試設置一些變量以發送以傳遞給函數。 我正在嘗試根據以下文檔使用.parent
和.val()
函數來設置customer_id
: https : .val()
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位置范圍之外的節點?
您不能只在數據庫引用上調用.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
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.