Cloud Function查询Firestore,但返回空数组

时间:2020-04-20 17:30:10

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

因此,我正在构建一个云函数,该函数接受一个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

1 个答案:

答案 0 :(得分:0)

您的函数有几处错误。

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

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

在进行了建议的更改之后,所需的功能代码将与现在的功能代码明显不同。

相关问题