Cloud Firestore collection count

后端 未结 17 1593
庸人自扰
庸人自扰 2020-11-22 09:25

Is it possible to count how many items a collection has using the new Firebase database, Cloud Firestore?

If so, how do I do that?

17条回答
  •  旧巷少年郎
    2020-11-22 09:58

    This uses counting to create numeric unique ID. In my use, I will not be decrementing ever, even when the document that the ID is needed for is deleted.

    Upon a collection creation that needs unique numeric value

    1. Designate a collection appData with one document, set with .doc id only
    2. Set uniqueNumericIDAmount to 0 in the firebase firestore console
    3. Use doc.data().uniqueNumericIDAmount + 1 as the unique numeric id
    4. Update appData collection uniqueNumericIDAmount with firebase.firestore.FieldValue.increment(1)
    firebase
        .firestore()
        .collection("appData")
        .doc("only")
        .get()
        .then(doc => {
            var foo = doc.data();
            foo.id = doc.id;
    
            // your collection that needs a unique ID
            firebase
                .firestore()
                .collection("uniqueNumericIDs")
                .doc(user.uid)// user id in my case
                .set({// I use this in login, so this document doesn't
                      // exist yet, otherwise use update instead of set
                    phone: this.state.phone,// whatever else you need
                    uniqueNumericID: foo.uniqueNumericIDAmount + 1
                })
                .then(() => {
    
                    // upon success of new ID, increment uniqueNumericIDAmount
                    firebase
                        .firestore()
                        .collection("appData")
                        .doc("only")
                        .update({
                            uniqueNumericIDAmount: firebase.firestore.FieldValue.increment(
                                1
                            )
                        })
                        .catch(err => {
                            console.log(err);
                        });
                })
                .catch(err => {
                    console.log(err);
                });
        });
    

提交回复
热议问题