首页 > 解决方案 > Firebase:doc.data() 返回空对象

问题描述

我正在开发一个 Firebase Cloud Function,以获取 Firestore 集合中的所有数据并将其放入 Firebase 实时数据库。

当我在 Firebase 函数模拟器中运行我的代码(在帖子的底部)时,第console.log9 行会打印一堆与一堆空对象配对的键,如下所示(实际 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()
    })
})

标签: javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


如果您在此处查看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()
    })

推荐阅读