Learn Courses My Dashboard

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

Hi everyone! 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? Thanks in advance!

you are using just “snapshot” variable name and not “querySnapshot” thats why it doesn’t exist, you should either change the querySnapshot to just snapshot or change snapshot to querySnapshot

Hi @fuerte.francis , thanks - this has helped me the first error. However despite changing “Querysnapshot” to ‘snapshot’ I am still getting the “Cannot find ‘function’ in scope” error.