【问题标题】:Cloud Function queries Firestore but returns empty arrayCloud Function 查询 Firestore 但返回空数组
【发布时间】:2020-04-20 17:30:10
【问题描述】:

所以我正在构建一个云函数,它接受一个 customerID,根据 customerID 过滤文档并返回文档列表。可悲的是它返回一个空数组。我相信这是一个简单的修复。

这里是云功能:

export const getCalendarItems = functions.https.onCall(async (data, context) => {
  const uid = data.uid;

  if (context.auth) {

    let array = [{}];

    const ref = admin.firestore().collection("photoshoots");
    const query = ref.where("customerID", "==", uid);
    query.onSnapshot((querySnapshot) => {
      querySnapshot.docs.forEach((documentSnapshot) => {
        array.push({
          ...documentSnapshot.data(),
          key: documentSnapshot.id,
        });
      });
    });

    return array;
  } else {
    return false;
  }
});

这是我从客户端调用它时的代码。

const uid = auth().currentUser.uid;

functions()
      .httpsCallable("getCalendarItems")({
        uid: uid
      })
      .then(result => {
        console.log(result.data);
      });

这里还有一个 Firestore 的屏幕截图。

Screenshot of firestore

【问题讨论】:

    标签: javascript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    你的函数有几个问题。

    首先,您不应使用 onSnapshot() 在 Cloud Functions 中进行查询。请改用get() 来执行一次查询。 onSnapshot() 附加一个监听器来实时接收更新,这不是你想要的。

    其次,您的函数需要返回一个承诺,该承诺会通过发送给客户端的数据进行解析。 get() 返回一个带有 QuerySnapshot 对象的承诺。您将需要使用它来获取与您的查询匹配的文档列表。您可以使用该列表将结果发送回客户端。

    在进行建议的更改后,您想要的函数代码看起来与现在的代码有很大不同。

    【讨论】:

    • 很高兴它有效。在 Stack Overflow 上,通常会将答案标记为正确,如果它们对您有帮助,请点赞。
    猜你喜欢
    • 2019-01-05
    • 2020-05-28
    • 2021-06-19
    • 2019-10-13
    • 2020-01-11
    • 2019-10-28
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    相关资源
    最近更新 更多