如何从 Firestore 获取数据到谷歌云函数?

时间:2021-02-02 15:52:39

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

我的 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);

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

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

找不到任何有关从 Firestore 获取数据到云函数的文档,但使用以下触发器的文档除外:onWrite。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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 函数中返回 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);吗?