首页 > 解决方案 > 如何在云功能中访问 firebase 数据库中的其他数据?

问题描述

我正在使用 Firebase 实时数据库并尝试在将名为的字段ignore添加到我的数据库时创建触发器。但我首先想访问数据库中的另一个数据并在我的函数中使用 if 。我的功能如下所示:

exports.dbTest2 = functions.database.ref('/{uid}/ignore')
  .onCreate((snapshot, context) => {

    const uid = context.params.uid
    console.log(`Current User ${uid}`)

    // Data added at the location
    const ignoreData = snapshot.val()
    const endTime = new Date(ignoreData.endTime).toString()

    const scheduleRef = snapshot.ref.parent.child('schedule')
    console.log(scheduleRef)

    let scheduleArr = [ /*something*/ ]
    return snapshot.ref.parent.child('schedule').set(scheduleArr)

  });

我的数据库看起来像这样:

在此处输入图像描述

从我当前的参考路径{uid}/ignore中,我想获取schedule参考中的第一个元素(在图像中圈出)。在上面的代码中,我尝试对引用进行控制台记录,但似乎没有这种方法可以从该对象获取值。

如何在我的云功能中获取图像中圈出的对象?

标签: javascriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


尝试functions.database.ref像这样嵌套:

exports.dbTest2 = functions.database.ref('/{uid}/ignore')
    .onCreate((snapshotIgnore, context) => {

      const uid = context.params.uid;

      admin.database().ref(`/${uid}/schedule`).once('value', snapshotSchedule => {
        console.log(snapshotSchedule.val()[0]);
      });
    });

推荐阅读