Firebase云功能进行数据库查询

时间:2018-06-24 20:36:46

标签: typescript firebase firebase-realtime-database google-cloud-functions

我正在尝试创建一个Firebase云函数,该函数根据节点的属性计算平均值。

这是我的实时数据库的结构

if let providerData = Auth.auth().currentUser?.providerData {
    for userInfo in providerData {
        switch userInfo.providerID {
        case "facebook.com":
            if !facebookProvider.accessToken.isEmpty {
                print("user is signed in with facebook")
            }
        case "google.com":
            if !googleProvider.accessToken.isEmpty {
                 print("user is signed in with google")
            }
        default:
            print("user is signed in with \(userInfo.providerID)")
        }
    }
}

为此,每次添加/删除/更新子节点(即评论)。我要检查rate属性并将其与其他Reviews的其余grade属性相加,然后将结果除以节点数。 ...最终结果将显示在名为finalResult的新属性中。

到目前为止,这是我的功能,但是我正在努力寻找一种查询数据库的方法,以便从其他节点获取成绩属性。你能帮我吗?

date 0101122315

1 个答案:

答案 0 :(得分:1)

请尝试以下功能,并让我知道

export const schoolUpdated = functions.database.ref('/buildings/{buildingId}/reviews/{buildingId}/rate').onWrite( (change, context) => {
    return Promise.all([admin.database().ref(`/buildings/${context.params.buildingId}/reviews`).once('value')]).then(r => {
      const allReviews = r[0];
      let sumScore = 0;
      let count = 0;
      allReviews.forEach(item => {
        sumScore += item.child('rate').val();
        count = count + 1;
      });
      let result = (sumScore / count);
      return change.after.ref.parent.parent.parent.child('finalResult').set(result);
    });
  });
相关问题