2

在我的Google Firebase Firstore数据库中,我想收集汇总数据,例如某个馆藏有多少个文件。由于Firestore不提供聚合查询,我试图编写一个云功能,每次将文档添加到数据库时将增加一个字段,该数据库将包含集合所具有的文档数量。在云端功能中访问云端Firestore文件

我遇到的问题是我无法为我的生活弄清楚如何从使用nodejs的云功能内的Firestore中获取文档。

下面是我在做什么:

在我index.js文件的顶部,我配置管理SDK和你有什么这样的:

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 

那么对于我的云功能,我这样做:

exports.createPost = functions.firestore 
    .document('posts/{post_id}') 
    .onCreate(event => { 

    // Get the post object 
    var post = event.data.data(); 

    var senderID = post["sender_id"]; // This is not null 

    // Access to user's document and the main ledger document 
    const userDocRef = admin.database().ref('/users').orderByChild("user_id").equalTo(senderID).once('value') 
    const ledgerDocRef = admin.database().ref('/posts/ledger').once('value'); 

    return Promise.all([userDocRef, ledgerDocRef]).then(snapshot => { 

     const user = snapshot[0].val(); 
     const ledger = snapshot[1].val(); 

     console.log("user => "+user); // Logs: user => null 
     console.log("ledger => "+ledger); // Logs: ledger => null 

     const userPostCount = user["user_name"]; 
     const globalPostCount = ledger["global_post_count"] + 1; 

     const userUpdate = user.update({"post_count" : userPostCount}); 
     const ledgerUpdate = ledger.update({"global_post_count" : globalPostCount}); 

     return Promise.all([userUpdate, ledgerUpdate]); 
    }); 
}); 

我结束了错误:

TypeError: Cannot read property 'global_post_count' of null at Promise.all.then.snapshot

我的数字意味着我的查询出了问题,但我不知道是什么。 usersposts都是根级集合。

林也越来越写着警告:

Billing account not configured. External network is not accessible and quotas are severely limited.

从我在线阅读,我不认为效果,但我认为这是值得一提。

请帮忙。

回答

6

看起来你已经写了一个公司的FireStore触发,但随后深入到实时数据库进行查询:

const userDocRef = admin.database().ref('/users').orderByChild("user_id").equalTo(senderID).once('value') 
const ledgerDocRef = admin.database().ref('/posts/ledger').once('value'); 

如果你的实时数据库是空的,这些疑问也将最终为空。

要查询Firestore,您需要使用admin.firestore()而不是admin.database()。公司的FireStore有mostly different API(通过云SDK我只是链接),比实时数据库,但它们在某些方面很相似。

+0

Ohhhh我现在看到那很漂亮。谢谢你的回答,在过去的几个小时里,我一直在撞墙。 –