【问题标题】:How to get data from firestore to google cloud functions?如何从 Firestore 获取数据到谷歌云功能?
【发布时间】:2021-05-06 19:59:12
【问题描述】:

我的 index.js 文件:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();

admin.initializeApp();

const db = admin.firestore();

 exports.getName = functions.https.onCall((data, context) => {
    var docRef = db.collection("dogs").doc("{data.id}");
    var getDoc = docRef.get().then(doc => {
        return doc.get("name");
    })
 });

flutter项目中的代码:

HttpsCallable callable = FirebaseFunctions.instance.httpsCallable("getName");
var temp = await callable({"id": "11"});
print(temp.data);

程序打印出 null,即使集合“dogs”中的文档存在,ID 为“11”,字段名称为。我正在尝试从 firestore 获取特定数据并将其返回。

控制台没有显示任何错误,如果我返回任何其他内容,它会正常打印出来。

除了使用诸如 onWrite 之类的触发器之外,找不到任何有关将数据从 firestore 获取到云功能的文档。

【问题讨论】:

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


    【解决方案1】:

    您是否尝试过使云功能异步?

    exports.getName = functions.https.onCall(async (data, context) => {
        var doc = await db.collection("dogs").doc("{data.id}").get();
        return doc.data().name;
     });
    

    【讨论】:

      【解决方案2】:

      andi2.2's 的答案是正确的,但让我解释一下为什么它不适用于使用 then() 的初始代码。

      通过做:

       exports.getName = functions.https.onCall((data, context) => {
          var docRef = db.collection("dogs").doc("{data.id}");
          var getDoc = docRef.get().then(doc => {
              return doc.get("name");
          })
       });
      

      您实际上并没有在 Callable Cloud Function 中返回 doc.get("name");then() 方法确实返回 Promise.resolve(doc.get("name")),如 then() doc 中所述,但您不会返回 Promise chain

      以下将起作用:

       exports.getName = functions.https.onCall((data, context) => {
          var docRef = db.collection("dogs").doc("{data.id}");
          return docRef.get().then(doc => {
              return doc.get("name");
          })
       });
      

      顺便说一句,你确定db.collection("dogs").doc("{data.id}"); 是正确的吗?不应该是db.collection("dogs").doc(data.id);吗?

      【讨论】:

        猜你喜欢
        • 2019-08-26
        • 2019-12-08
        • 2020-05-18
        • 2019-06-04
        • 2020-04-28
        • 1970-01-01
        • 2018-06-30
        • 2021-03-06
        • 1970-01-01
        相关资源
        最近更新 更多