How can I return a count of second level collection documents in Firebase?

Viewed 61

I am trying to provide a count of the number of items in the ‘Products’ collection for each user, and display this in a label on the UI of my app. This is how my Firebase database is structured:

Users

  • user 1

    products
    • product 1
    • product 2
  • user 2

    products
    • product 1

So for example, when user 1 logs in, it will display that they have 2 products, whereas when user 2 logs in, it will display that they have 1 product.

Below is my code which is used to return this data for each user.

document.reference.collection("products").get().then(function(querySnapshot) {

However, I am getting the below errors for this line of code.

Error 1 - “Cannot find 'querySnapshot' in scope”
Error 2 - “Cannot find 'function' in scope”

Here is my full method I am using to retrieve and display a count of items for the currently signed in user.

    func databaseCount() {

        let db = Firestore.firestore()

        let user = Auth.auth().currentUser

        db.collection("users").getDocuments { (snapshot, error) in
                if let error = error {
                    print(error)
                    return
                } else {
                    for document in snapshot!.documents {
                        let data = document.data()
                        let userId = data["uid"] as! String
                        if userId == user?.uid {
                            document.reference.collection("products").get().then(function(querySnapshot) {
                                console.log(querySnapshot.size);

                                let itemCount = data(querySnapshot.size) as! String
                                self.welcomeLabel.text = "Your item count is \(itemCount)!"
                            });
                        }
                    }
                }
            }
    }

How would I go about updating my code to achieve my intended goal?

1 Answers

What i usually do in such scenarios is, When you create document in Users collection create an extra field of name cartItemCount with value 0 by default. In your case productsCount.

Users
---------user1
------------------name     
------------------email
------------------productCount
------------------Products
--------------------------------product1

So when ever a document is added to Product collection of a User. Increment the value of productsCount by 1 and decrement by 1 if document is removed using the reference to that user document.

FieldValue.increment(Int64(1))

FieldValue.increment(Int64(-1))

Related