How do I design a simple Firebase Database that stores arrays?

前端 未结 1 781
执念已碎
执念已碎 2020-12-06 16:12

I am in the midst of coding an IOS application using Xcode 8.2.1 in Swift. Currently, I have the database set up for one view controller that implements GeoFire and successf

相关标签:
1条回答
  • 2020-12-06 16:32

    Read this: Arrays are evil

    In general it's best of avoid them as there are usually better ways to organize your data.

    Here's some info:

    This creates a node called child_node and assigns it a value of some_value

    let ref = FIRDatabase.database().reference()
    let childRef = ref.child("child_node")
    childRef.setValue("some_value")
    

    results in

    root
      child_node: some_value
    

    If you run the code again, it will overwrite the existing node.

    In general it's best to disassociate nodes names from the data they contain so expanding a bit

    let ref = FIRDatabase.database().reference()
    let childRef = ref.childByAutoId()
    childRef.setValue("some_value")
    

    results in

    root
       -Y8hjj9a99js9jd: some_value
       -Yi00ksomosooss: some_value //the second time it's run
    

    And then to go a bit further

    let ref = FIRDatabase.database().reference()
    let childRef = ref.childByAutoId()
    let someData = ["site": "Olympus Mons", "location": "Mars"]
    childRef.setValue(someData)
    

    results in

    root
       -Y88ujs9mskkms:
             site: "Olympus Mons"
             location: "Mars"
    

    So you then ask yourself 'self, what does this have to do with arrays'?

    It's a better way to store 'extra' data. So for example you could store a users location within their node

    root
      users
         -Yi8joiomso (uid)
             g: xxxx
             l:
               0: xxx
               1: xxx
    

    or keep a reference to where they are in another node

    root
      users
         -Yi8joiomso (uid)
           location: -Yiuhj89ejee
      location
         -Yiuhj89ejee
             g: xxxx
             l:
               0: xxx
               1: xxx
    

    or keep the users within the location node

    root
      location
        userID
           g: xxxx
           l:
              0: xxxx
              1: xxxx
    

    Non-array structures give far more flexibility for queries, retrieving data and organizing data.

    0 讨论(0)
提交回复
热议问题