2017-10-17 159 views
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我現在看到那很漂亮。謝謝你的回答,在過去的幾個小時裏,我一直在撞牆。 –