Firebase:doc.data()返回空对象

时间:2018-08-16 05:06:17

标签: javascript firebase google-cloud-firestore google-cloud-functions

我正在使用Firebase Cloud Function来获取Firestore集合中的所有数据,并将其放入Firebase实时数据库中。

当我在Firebase函数仿真器中运行代码时(在文章的底部),第9行上的console.log打印出一堆配对到一堆空对象的键,就像这样(编辑了实际ID) ):

{ 
 '<some id>': {},
 '<some other id>': {},
 <bunch of other entries>...
}

这对我来说没有意义,因为documentation并未说明为什么应返回一个空对象。我的文档确实存在,为什么我不能获取他们的数据?

以下是带有问题段的源代码:

 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()
    })
})

2 个答案:

答案 0 :(得分:2)

如果您在此处检查firebase docs。用于查询集合中多个文档的代码示例为:

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()
    })

答案 1 :(得分:0)

Firestore快照到对象:

true
相关问题