Firebase – 如何在observeEventType = Value中获取关键值

这是Firebase的后续问题- 构build数据库的正确方法

我有以下DB结构:

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

我想查询艺术家参考,看看艺术家是否已经在数据库中,如果艺术家是在数据库中,获取艺术家的关键(在上面的例子中,它将是-KKMkpA22PeoHtBAPyKm )。

我试过这个:

 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") } }) 

但是“snapshot.key”只给出了“艺术家”的父键。

我怎样才能得到我需要的钥匙?

如果条件,你需要得到所有键得到“-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") } 

这是一个解决scheme。

 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) } } })