2017-12-06 14 views
2

コレクション内のドキュメントの量を追跡するクラウド機能を作成しようとしています。 Firestoreのためにおそらくこれについてのドキュメンテーションのトンは今ではありません..私はこれを行うための最善の方法を考えようとしていました。これは私が思い付く解決策です。私は理解できませんそこに理想的なコレクション内のドキュメントの数を格納しますが、私はこのFirestoreクラウドの機能 - コレクション内のドキュメントの数を維持する

に関連する方法を見つけ出すように見えることはできません文献1では>ドキュメント

- >コレクション - 数

文献1を返す方法

+1

[Cloud Firestoreでコレクション内のドキュメント数を取得する方法](https://stackoverflow.com/questions/46553314/how-to-get-a-count-of-number-クラウド・ファイアストアを備えたコレクション・オブ・ア・コレクション・オブ・クラウド・ファイアストア) –

答えて

2

Document1がブログ投稿であり、サブコレクションがコメントであると仮定しよう。

  1. コメントdoc createで関数をトリガーします。
  2. 親ドキュメントを読み取り、既存のカウントをインクリメントします。
  3. 親ドキュメントにデータを書き込みます。

注:お使いのカウント値が速く、一度毎秒よりも変化した場合、あなたはhttps://firebase.google.com/docs/firestore/solutions/counters

exports.aggregateComments = functions.firestore 
    .document('posts/{postId}/comments/{commentId}') 
    .onCreate(event => { 

    const commentId = event.params.commentId; 
    const postId = event.params.postId; 

    // ref to the parent document 
    const docRef = admin.firestore().collection('posts').doc(postId) 


    return docRef.get().then(snap => { 

      // get the total comment count and add one 
      const commentCount = snap.data().commentCount + 1; 

      const data = { commentCount } 

      // run update 
      return docRef.update(data) 
    }) 

}); 

分散カウンタを必要とするかもしれないあなたは、高度な集計計算を実行する必要がある場合、私は、詳細なfirestore aggregation exampleをまとめます簡単な数を超えて

関連する問題