2
votes

This is a follow up question to Firebase - proper way to structure the DB

I have the following DB structure:

"artists" : {
  "-KKMkpA22PeoHtBAPyKm" : {
    "name" : "Skillet"
  }
}

And I want to query the artists ref and see if an artist is already in the DB or not and if the artist IS in the DB, get the artist key (in the above example it would be -KKMkpA22PeoHtBAPyKm).

I tried this:

artistsRef.queryOrderedByChild("name").queryEqualToValue("Skillet").observeEventType(.Value, withBlock: { (snapshot) in
        if snapshot.exists() {
            print("we have that artist, the id is \(snapshot.key)")
        } else {
            print("we don't have that, add it to the DB now")
        }
    })

but "snapshot.key" only gives me the parent key which is "artists".

How can I get the key I need?

3

3 Answers

4
votes

Here's a solution.

let ref = self.myRootRef.childByAppendingPath("artists")

ref.queryOrderedByChild("name").queryEqualToValue("Skillet")
     .observeEventType(.Value, withBlock: { snapshot in

     if ( snapshot.value is NSNull ) {
          print("Skillet was not found")
     } else {
          for child in snapshot.children {   //in case there are several skillets
               let key = child.key as String
               print(key)
          }
     }
})
4
votes

In if condition, you need to get allKeys to get "-KKMkpA22PeoHtBAPyKm" ...

    if snapshot.exists() {
        for a in (snapshot.value?.allKeys)!{
            print(a)
        }
    } else {
        print("we don't have that, add it to the DB now")
    }
0
votes
You can get the Keys with the help of Dictionary itself.

    Database.database().reference().child("artists").observe(.value, with: { (snapshot) in
        if snapshot.exists() {
            if let artistsDictionary = snapshot.value as? NSDictionary {
                for artists in artistsDictionary.keyEnumerator() {
                    if let artistsKey = artists as? String {
                        print(artistsKey) // Here you will get the keys.
                    }
                }
            }
        } else {
            print("no data")
        }
    }) { (error) in
        print(error)
    }