【问题标题】:How to access Cloud Firestore from a Cloud Function?如何从 Cloud Function 访问 Cloud Firestore?
【发布时间】:2018-06-22 19:02:30
【问题描述】:

我正在尝试从我的 Cloud Firestore 中检索数据以最终在 GraphQL 服务器中使用,但现在我只是返回 JSON 进行测试。我正在使用以下代码访问 Firestore,但似乎没有取回任何数据。我知道该功能正常工作,因为“开始测试”和“最终测试推送”按预期出现在 JSON 响应中。

我也尝试过使用 Admin SDK 说明,但无济于事。谁能发现我在这里做错了什么?

import * as admin from "firebase-admin"
import * as functions from "firebase-functions"

admin.initializeApp(functions.config().firebase)
const db = admin.firestore()

const authors = [{ key: "start test" }]
db.collection("authors")
    .get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            const data = {
                id: doc.id,
                firstName: doc.firstName,
                lastName: doc.lastName
            }
            authors.push(data)
            authors.push({ key: "test in loop" })
        })
    })
authors.push({ key: "final test push" })

export default authors

非常感谢!

编辑:我应该注意这是来自一个单独的 getter 文件。 Cloud Function 本身位于其他位置并且工作正常。

编辑#2:云函数定义

import authorsArray from "./firestore"

const testServer = express()
testServer.get("*", (req, res) => {
    res.setHeader("Content-Type", "application/json")
    res.send(JSON.stringify({ data: authorsArray }))
})
const test = https.onRequest(testServer)

【问题讨论】:

  • 我在这里没有看到云函数定义。您不能只是将任意代码推送到 Cloud Functions 以执行 - 您必须声明某种触发器来定义函数的执行时间。
  • 这是你index.js文件的全部内容吗?
  • 对不起,我应该更清楚一点:这是一个单独的 getter 文件。云函数本身在其他地方定义并且工作正常。

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


【解决方案1】:

尝试如下修改代码;因为快照数据是doc.data(),id 是doc.id

db.collection("authors")
    .get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            const data = {
                id: doc.id,
                firstName: doc.data().firstName,
                lastName: doc.data().lastName
            }
            authors.push(data)
            authors.push({ key: "test in loop" })
        })

请查看link 以供参考

【讨论】:

  • 谢谢!它现在正在工作,但仅在硬刷新后的第二次加载时。 Firestore 的数据也在“最终测试推送”之后出现。我猜这是因为异步获取?
  • 是的,完全正确。 :)
  • 如何让它在返回响应之前等待数据?我不确定在 getter 文件或云函数本身(添加到主帖)中添加 async/await 的位置
  • 我想如果你向上移动最后一排。它将等待 foreach 循环。或者您可以通过以下方式检查 count nr:snapshot.forEach((doc, countnr) =>...
  • 还是同样的问题,在 Firestore 数据包含在结果中之前需要刷新几次.. :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
  • 2019-04-12
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
相关资源
最近更新 更多