【问题标题】:How to get data from Firestore in Cloud Function?如何从 Cloud Function 中的 Firestore 获取数据?
【发布时间】:2018-11-21 16:52:19
【问题描述】:

我需要知道我在这里做错了什么?

我从 Flutter 调用这个函数。回调正确完成,第一次和第二次打印出现在 Firbase 的“日志”中。但是从“Firestore”中得到未定义!!

这是云函数中的代码:

var functions = require("firebase-functions");
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
admin.firestore().settings({ timestampsInSnapshots: true });


exports.storeContact5 = functions.https.onCall((data, context) => {
    // First print is working fine
    console.log('test');
    var recieverId = 'WqHxLoYvRxR9UK8sFJZ9WxTOIE32';
    const check = admin.firestore().collection('users').doc(recieverId).get();
    check.then(testValue => {
        console.log(testValue.data.nickname);
        return true;
    }).catch(err => {
        console.log('Error getting document', err);
    });
    console.log('test2');
    // Return to flutter App (Working fine)
    return {
        repeat_message: 'ok!'
    }
});

Firebase 日志的屏幕截图

【问题讨论】:

  • @RahulMahadik - 这是云函数代码!

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


【解决方案1】:

您应该使用testValue.data().nickname 而不是testValue.data.nickname,请参阅https://firebase.google.com/docs/firestore/query-data/get-data#get_a_documenthttps://firebase.google.com/docs/reference/js/firebase.firestore.DocumentSnapshot#data

另外,如果你想返回异步操作的结果,你应该只返回一次结果,并且你不应该在.then()之外返回。

另外,看这里如何处理错误:https://firebase.google.com/docs/functions/callable#handle_errors

所以你可以这样做:

exports.storeContact5 = functions.https.onCall((data, context) => {
    // First print is working fine
    console.log('test');
    var recieverId = 'WqHxLoYvRxR9UK8sFJZ9WxTOIE32';
    const check = admin.firestore().collection('users').doc(recieverId).get();
    return check.then(testValue => {
        console.log(testValue.data().nickname);
        return {repeat_message: 'ok!'};
    }).catch(err => {
        console.log('Error getting document', err);
        throw new functions.https.HttpsError('Error getting document', err);
    });
});

我建议你观看官方系列的视频:https://firebase.google.com/docs/functions/video-series/,尤其是标题为“Learn JavaScript Promises”的视频

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多