How do I design a simple Firebase Database that st

2020-02-01 07:24发布

问题:

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 successfully adds locations to the database. On a separate view controller, I want to add a reference to the same database and add children to this reference.

This separate reference I want to store different arrays that can be accessed by the array name. I want to be able to add and remove the saved arrays in the database. In addition, I want to be able to add and remove the strings that are held in each individual array.

The code that I have tried is:

    let ref = FIRDatabase.database().reference()

    let childRef = FIRDatabase.database().reference(withPath: "arrays")

    let itemsRef = ref.child("arrays")

    let milkRef = itemsRef.child("array1")

But when I run this code, the database does not update to show any new children. Is it possible to accomplish my task? If so, what am I doing wrong?

If my question is unclear in any way please let me know and I will be willing to elaborate. Thank you in advance for any help!

回答1:

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.