简体   繁体   中英

How to get data from firestore to google cloud functions?

My index.js file:

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");
    })
 });

Code in the flutter project:

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

The program prints out null, even though document in collection "dogs" with id "11" with a field name exists. I'm trying to get specific data from firestore and return it.

Console doesn't show any errors and if I'd return anything else it would print out normally.

Couldn't find any documentations about getting data from firestore to cloud function other than ones that use triggers like: onWrite.

Have you tried to make the cloud function async?

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

andi2.2's answer is correct, but let me explain why it doesn't work with your initial code using then() .

By doing:

 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");
    })
 });

You actually don't return doc.get("name"); in your Callable Cloud Function. The then() method does return Promise.resolve(doc.get("name")) , as explained in the then() doc , but you don't return the Promise chain .

The following will work:

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

BTW, are you sure that db.collection("dogs").doc("{data.id}"); is correct? Shouldn't it be db.collection("dogs").doc(data.id); ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM