Firebase firestore collection count with angularFire 2

廉价感情. 提交于 2019-12-12 14:29:59

问题


I want to get the total number of the documents that exist in firestore. I don't want to get the data only the total number of inside Products collection I have 200.000 items is that possible with Angular 4-5, not angular.js

Can someone expert tell me how I can achieve that ??

My code so far and is not work

  get_total_messages() {
    this.messages_collection = this.afs.collection<MessageEntity>('messages');
    return this.messages_collection.snapshotChanges();
  }

End this is how I try to get the data but is not what I want;

this.firebase_Service.get_total_messages().subscribe( data => {
   console.log(data);
});

回答1:


There is no API to get the count of the number of documents in a Firestore collection. This means that the only ways to get the count are:

  1. Get all documents and count them client-side.
  2. Store the count as a separate property and update that as you add/remove documents.

Both approaches are quite common in NoSQL databases, with the second of course being a lot more efficient as the number of documents grows.

Firebase provides a sample of using Cloud Functions to keep a counter. While this sample is written for the Firebase Realtime Database, it can easily be modified to work on Cloud Firestore too.

Firestore also provides documentation on running aggregation queries and running distributed counters. Both seem slightly more involved than the first sample I linked though.




回答2:


this.firebase_Service.get_total_messages().subscribe( data=>this.totalnumber=data.length); //now, you can get total number of messages



来源:https://stackoverflow.com/questions/47378910/firebase-firestore-collection-count-with-angularfire-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!