javascript - Firebase:doc.data() 返回空对象
问题描述
我正在开发一个 Firebase Cloud Function,以获取 Firestore 集合中的所有数据并将其放入 Firebase 实时数据库。
当我在 Firebase 函数模拟器中运行我的代码(在帖子的底部)时,第console.log
9 行会打印一堆与一堆空对象配对的键,如下所示(实际 ID 已编辑):
{
'<some id>': {},
'<some other id>': {},
<bunch of other entries>...
}
这对我来说没有意义,因为文档没有说明为什么它应该返回一个空对象。我的文档确实存在,为什么我无法获取他们的数据?
这是注释有问题的段的源代码:
exports.generateCache = functions.https.onRequest((req, res) => {
admin.firestore().collection('parts').select().get()
.then(snapshot => snapshot.docs)
.then(docs => {
// this is the problematic segment of code
var cache = {}
docs.forEach(doc => {
cache[doc.id] = doc.data()
})
console.log(cache)
return cache
})
.then(cachedData => storeCachedData(cachedData))
.then(() => {
res.send('done!')
res.end()
})
})
解决方案
如果您在此处查看firebase 文档。查询集合中的多个文档的代码示例是:
db.collection("cities").where("capital", "==", true)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
所以在你的情况下,尝试改变这个:
.then(snapshot => snapshot.docs)
.then(docs => {
// this is the problematic segment of code
var cache = {}
docs.forEach(doc => {
cache[doc.id] = doc.data()
})
对此
.then(snapshot => {
var cache = {}
snapshot.forEach(doc => {
cache[doc.id] = doc.data()
})
推荐阅读
- java - 如何输入字符串数据?
- javascript - 币安 API Hmac 签名
- apache-kafka - 在日志压缩的情况下,Kafka 回复如何工作?
- java - 如何将此 switch 语句交换为多态方法?
- java - 通过单击另一个 JFrame 窗口中的按钮打开一个新的 JFrame 窗口
- python - 如何以正确的格式获取 YouTube 上传的日期?
- android - 从 GET 获取状态码 400
- angular - Angular5 - 如何将 ASYNC 数据从父组件传递到子组件
- jquery - 如何通过在 Jquery 中附加或从 AJAX 返回来显示上传?
- ruby-on-rails - Heroku 上的 RoR:为什么 ModelOne.count 仅在生产中不能在 ModelTwo 中工作?