【问题标题】:Retrieve Data from Firestore by Using Cloud Functions HTTP Trigger使用 Cloud Functions HTTP 触发器从 Firestore 检索数据
【发布时间】:2019-08-11 06:45:39
【问题描述】:

我的代码在db.collection("OrderId").doc("D9XjS3efiV12epxQcgYA").get().then 之前运行良好,因为当我取消注释该行时它返回“firestoreFunc runnig”,但没有记录并且在db.collection("OrderId").doc("D9XjS3efiV12epxQcgYA").get().then 内没有返回任何内容。

如何使用 HTTP 触发器访问 Firestore?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.firestoreFunc = functions.https.onCall((data, context) =>  {
    //return "firestoreFunc running";
    db.collection("OrderId").doc("D9XjS3efiV12epxQcgYA").get().then(snapshot =>  {

        console.log("log : 22");

        return 22;
    }).catch(reason =>  {

    })
});

【问题讨论】:

  • 我无法从您所写的内容中确切看出您打算如何处理您获取的文档。您的可调用函数不会向客户端返回任何内容(根据您在此处显示的内容)。如果您确实想根据 fetch 文档返回某些内容,则需要正确处理 Promise(您不在这里 - 该函数将在文档可用之前返回)。你到底想完成什么?
  • 我正在尝试从文档中的“groupId”字段获取数据。我以为它会返回 22 (用于测试)。你能解释一下为什么函数在文档可用之前就返回了吗?

标签: javascript node.js google-cloud-firestore google-cloud-functions


【解决方案1】:

您的函数必须返回一个用您要发送给客户端的数据解析的承诺。如现在所示,您的函数不返回任何内容,并且文档获取可能不会完成,因为函数将被终止,因为它不知道等待获取。

只需从 get() 返回的 promise 中添加一个 return:

return db.collection("OrderId").doc("D9XjS3efiV12epxQcgYA").get().then(snapshot =>  {
    console.log("log : 22");
    return 22;
}).catch(reason =>  {
    // you should handle errors here
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2019-04-12
    • 2020-08-15
    • 2017-11-26
    • 2018-10-16
    • 2020-02-04
    • 2019-11-13
    相关资源
    最近更新 更多