首页 > 解决方案 > 从 Cloud Functions 实时数据库中的子引用获取父节点的原始值“val()”数据

问题描述

假设我在 typescript/javascript 代码函数中指向如下路径:

exports.sendNotification = functions.database.ref('shops/countries/{countryName}/shopAddress/{currentShopAddress}')
.onWrite((snapshot,context) => {

    // Is it possible to get the data raw value from a child reference node? 
    // For example: 
    const countryName = snapshot.before.parent('countryName').val();
    // Then
    const countryId = countryName['countryId'];
})

我是 node.js/typescript 和 firebase 云功能新手 :)

标签: node.jstypescriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


数据库中父节点的数据不会自动传递到您的 Cloud Function 中,因为您可能是大量不需要的数据。

如果你需要它,你需要自己加载它。幸运的是,这并不难:

const countryRef = snapshot.ref.parent.parent;
const countryName = countryRef.key; // also available as context.params.countryName
countryRef.child('countryId').once('value').then((countryIdSnapshot) => {
  const countryId = countryIdSnapshot.val();
});

请注意,由于您异步加载其他数据,因此您需要返回一个承诺以确保您的函数不会过早关闭。


推荐阅读