[Solved] Fetch all children from database


This answer is similar to a prior answer here

What you want to do is to treat each child in Customers as a DataSnapshot, then the children can be accessed.

Given a Firebase structure:

usersDatabase
  uid_0
     Customers
        Ben Smith
           data: "Some data"
        Tom Cruise
           data: "Some data"
  uid_1
     Customers
        Leroy Jenkins
           data: "Some data"
  uid_2
     Customers
        De Kelly
           data: "Some data"
     etc

The code to print out each user and their customers is

let usersDatabaseRef = Database.database().reference().child("usersDatabase")
usersDatabaseRef.observe(.value, with: { snapshot in
    print("there are \(snapshot.childrenCount) users")
    for child in snapshot.children {
        let childSnap = child as! DataSnapshot
        print("user: \(childSnap.key)")
        let userCustomerSnap = childSnap.childSnapshot(forPath: "Customers")
        for customer in userCustomerSnap.children {
            let customerSnap = customer as! DataSnapshot
            print(" customer: \(customerSnap.key)")
        }
    }
})

and the output

there are 3 users
user: uid_0
 customer: Ben Smith
 customer: Tom Cruise
user: uid_1
 customer: Leroy Jenkins
user: uid_2
 customer: De Kelly
 customer: Leonard Nimoy
 customer: William Shatner

Edit: the OP wanted to know how to get to the data node under each customer so here’s a slightly modified version with output

let usersDatabaseRef = Database.database().reference().child("usersDatabase")
usersDatabaseRef.observe(.value, with: { snapshot in
    print("there are \(snapshot.childrenCount) users")
    for child in snapshot.children {
        let childSnap = child as! DataSnapshot
        print("user: \(childSnap.key)")
        let userCustomerSnap = childSnap.childSnapshot(forPath: "Customers")
        for customer in userCustomerSnap.children {
            let customerSnap = customer as! DataSnapshot
            let dict = customerSnap.value as! [String: Any]
            let value = dict["data"] as! String

            print(" customer: \(customerSnap.key)")
            print("    and their data is: \(value)")
        }
    }
})

and the output

there are 3 users
user: uid_0
 customer: Ben Smith
    and their data is: some data
 customer: Tom Cruise
    and their data is: some data
user: uid_1
 customer: Leroy Jenkins
    and their data is: some data
user: uid_2
 customer: De Kelly
    and their data is: some data
 customer: Leonard Nimoy
    and their data is: some data
 customer: William Shatner
    and their data is: some data

9

solved Fetch all children from database