[英]How to get data from Firestore in Cloud Function?
我需要知道我在做什么错吗?
我从Flutter调用此函数。 回调已正确完成,第一和第二个打印记录在Firbase的“日志”中。 但是从“ Firestore”中变得不确定!
这是Cloud Function中的代码:
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日志的屏幕截图
您应该使用testValue.data().nickname
而不是testValue.data.nickname
,请参阅https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document和https://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”的视频
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.