Firebase Firestore 返回 QuerySnapshot

TIJ*_*TIJ 0 javascript node.js firebase google-cloud-functions google-cloud-firestore

我刚刚开始使用 firebase 云函数和 firestore,但是当我在 firebase 云函数中使用 firestore (如下代码)时,它返回和 QuerySnapshot 而不是返回数据。如果有人以前遇到过这个问题并且已经解决了,请告诉我。这也将帮助我解决这个问题。

谢谢。

export async function allRestaurants(req: Request, res: Response) {
  try {
    // const { id } = req.params
    const restaurantsRef = admin.firestore().collection('restaurants');
    const snapshot = await restaurantsRef.get();

    console.log(">>>>>>>>>", snapshot);
    return res.status(200).send({ data: { restaurants: snapshot } })
  } catch (err) {
    return handleError(res, err)
  }
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*nec 5

得到 a 是正常的QuerySnapshot,因为该get()方法返回一个用 a 解析的 Promise QuerySnapshot

您可以自行生成要发送回 Cloud Function 使用者的内容。

例如,您可以使用forEach()方法来循环QuerySnapshot,或者如下所示,使用docs数组。

export async function allRestaurants(req: Request, res: Response) {
  try {
    // const { id } = req.params
    const restaurantsRef = admin.firestore().collection('restaurants');
    const snapshot = await restaurantsRef.get();

    const responseContent = snapshot.docs.map(doc => doc.data());

    return res.status(200).send({ data: { restaurants: responseContent } })
  } catch (err) {
    return handleError(res, err)
  }
}
Run Code Online (Sandbox Code Playgroud)