器上运行的Firebase"/>
使用在Firestore模拟器上运行的Firebase
当我在客户端]上使用firebase.firestore()
时,以下功能运行良好,并设法找到了文档:
带有firebase.firestore()
function getUserProfile(email, returnDoc) { var db = firebase.firestore(); var docRef = db.collection("Users").doc(email); docRef.get().then(function (doc) { if (doc.exists) { returnDoc(undefined, doc); } else { returnDoc("User not found.", doc); } }).catch(function (error) { returnDoc("Error getting user.", doc); }); };
在
index.js
具有相同getUserProfile(user.email, function (err, userProfile) { if (!err) { $scope.firstName = userProfile.get("FirstName"); $scope.lastName = userProfile.get("LastName"); $scope.email = userProfile.get("Email"); $scope.$apply(); } else { alert(err); }; });
但是当我尝试使用
firebase-admin
创建另一个相似的函数时,以下函数找不到
email
参数的文档:在db.js
中并带有admin.firestore()
const admin = require('firebase-admin'); admin.initializeApp(); let db = admin.firestore(); function getUserData(email, returnDoc) { console.log(`imtp-db.getUserData: ${email}`); // email data is correct and exist in database. let docRef = db.collection("Users").doc(email); return docRef.get().then(function (doc) { console.log(`doc.exists: ${doc.exists}`); // doc.exists: false here. if (doc.exists) { console.log("Document data:", doc.data()); return returnDoc(undefined, doc); } else { return returnDoc("User not found.", doc); }; }).catch(function (error) { return returnDoc("Error getting user.", doc); }); }; exports.getUserData = getUserData;
在云端功能:
const functions = require('firebase-functions'); const db = require("./middleware/db.js"); exports.getUserProfile = functions.https.onCall((data, context) => { var userProfile = undefined; console.log(`data.email = ${data.email}`); return db.getUserData(data.email, function (err, userDoc) { console.log(`exports.getUserProfile.err = ${err}`); if (!err) { userProfile = userDoc.data(); return { error: err, returnData: userProfile }; } else { return { error: err, returnData: userProfile }; }; }); });
在上述功能中,一切正常,没有错误,除了
doc.exists
始终计算为false
并始终返回"User not found."
,为什么?我在第二版代码中做错了什么?谢谢!
NOTE:
我正在运行所有仿真器:firebase emulators:start
当我在客户端上使用firebase.firestore()时,以下函数运行良好,并设法找到了该文档:使用firebase.firestore()函数getUserProfile(email,returnDoc){var db = ...
回答如下:关于this post,显然,答案很简单:本地Firestore仿真器没有数据
。基于问题中完全相同的代码,可以使用以下方法轻松证明这一点:更多推荐
使用在Firestore模拟器上运行的Firebase
发布评论