[英]Firebase: doc.data() returns empty object
我正在使用 Firebase Cloud Function 来获取 Firestore 集合中的所有数据并将其放入 Firebase 实时数据库中。
当我在 Firebase 函数模拟器中运行我的代码(在帖子的底部)时,第 9 行的console.log
打印一堆与一堆空对象配对的键,如下所示(实际 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()
})
Firestore 快照到对象:
db.collection('collection').then(snapshot =>
const docsDictionary = (snapshot.docs || []).reduce((prev, doc) => ({ ...prev, [doc.id]: doc.data() }), {})
// ...do stuff
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.