检索 Firebase 数据的更有效方法?

More efficient way to retrieve Firebase Data?

我有一组分层数据,我想从 Firebase 检索信息。下面是我的数据:

但是,我的问题是:在查看数据的结构后,当我想获取 attendeenameobject id 时,我必须执行以下代码:

func getAttendees(child: NSString, completion: (result: Bool, name: String?, objectID: String?) -> Void){
    var attendeesReference = self.eventsReference.childByAppendingPath((child as String) + "/attendees")

    attendeesReference.observeEventType(FEventType.ChildAdded, withBlock: { (snapshot) -> Void in

        //Get the name/object ID of the attendee one by one--inefficient?
        let name = snapshot.value.objectForKey("name") as? String
        let objectID = snapshot.value.objectForKey("objectID") as? String
        if snapshot != nil {
            println("Name: \(name) Object ID: \(objectID)")
            completion(result: true, name: name, objectID: objectID)
        }

        }) { (error) -> Void in
            println(error.description)
    }   
}

现在这会遍历每个与会者 child 并一一获取姓名和 object id。函数完成后,我将每个值存储到字典中。这样做后,此函数会被多次调用,并且可能会非常慢,尤其是在多次访问 to/from 数据库时。有没有更有效的方法来做到这一点?我试图查看 FEeventType.Value,但这似乎 return attendees child 中的所有内容,而我真正想要的只是 name 和 [=17] =] 的每个 attendee 存储到某种字典中。任何帮助,将不胜感激。谢谢!

Firebase 的黄金法则之一是 仅当您总是想检索所有数据时才嵌套数据。这条规则的原因是 Firebase 总是 returns 一个完整的节点。您不能部分检索该节点中的某些数据而不是其他数据。

Firebase guide on structuring data,是这样说的:

Because we can nest data up to 32 levels deep, it's tempting to think that this should be the default structure. However, when we fetch data at a location in our database, we also retrieve all of its child nodes. Therefore, in practice, it's best to keep things as flat as possible, just as one would structure SQL tables.

您真的应该阅读文档的整个部分,因为它包含一些非常好的示例。

对于您的情况,您需要修改数据结构以将活动参与者与活动元数据分开:

events
  -JFSDFHdsf89498432
    eventCreator: "Stephen"
    eventCreatorId: 1764137
  -JOeDFJHFDSHJ14312
    eventCreator: "puf"
    eventCreatorId: 892312
event_attendees
  -JFSDFHdsf89498432
    -JSAJKAS75478
      name: "Johnny Appleseed"
    -JSAJKAS75412
      name: "use1871869"
  -JOeDFJHFDSHJ14312
    -JaAasdhj1382
      name: "Frank van Puffelen"
    -Jo1asd138921
      name: "use1871869"

这样,您可以在不检索与会者的情况下检索事件元数据,反之亦然。