Maro0osha Maro0osha - 2 months ago 26
JSON Question

Accessing to the users uid in Firebase

I have this JSON structure:

{
"Devices" : {
"1EJ8QmEQBJfBez7PMADbftCjVff1" : {
"Device1" : {
"Category" : "Others",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : ""
},
"Device2" : {
"Category" : "Chairs",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : ""
},
"Device3" : {
"Category" : "Others",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : ""
}
},
"97PUAcUC5UYxLpBOLnC4yQjxiEf2" : {
"Device1" : {
"Category" : "Others",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : ""
},
"Device2" : {
"Category" : "Books",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : ""
},
"Device3" : {
"Category" : "Chairs",
"Description" : "",
"DeviceName" : "",
"ImageUrl" : ""
}
}
},
"UserProfile" : {
"1EJ8QmEQBJfBez7PMADbftCjVff1" : {
"city" : "",
"email" : "",
"name" : "",
"phone" : ""
},
"97PUAcUC5UYxLpBOLnC4yQjxiEf2" : {
"city" : "",
"email" : "",
"name" : "",
"phone" : ""
},
}
}


I want to access to the Category node in each device?
Is that possible?
Because I want to retrieve data for all nodes that have the same category!

let ref = FIRDatabase.database().reference().child("Devices")

ref.queryOrderedByChild("Category")


I have tried to access to devices! then direct to the category!
It seems like this is not the correct way!

Don't tell me that I need to change the structure of the JSON!

Is there any way to access to the user ids'?

Answer

In NoSQL databases you will often have to model your data for the use-cases that you app needs. With your current data structure you can efficiently load a user's devices.

To also efficiently allow to load the devices for a category, you will have to store that information too. Here's one way to do that:

"Categories": {
  "Others": {
    "1EJ8QmEQBJfBez7PMADbftCjVff1_Device1": "1EJ8QmEQBJfBez7PMADbftCjVff1/Device1",
    "1EJ8QmEQBJfBez7PMADbftCjVff1_Device3": "1EJ8QmEQBJfBez7PMADbftCjVff1/Device3",
    "97PUAcUC5UYxLpBOLnC4yQjxiEf2_Device1": "97PUAcUC5UYxLpBOLnC4yQjxiEf2/Device1"
  },
  "Chairs": {
    "1EJ8QmEQBJfBez7PMADbftCjVff1_Device2": "1EJ8QmEQBJfBez7PMADbftCjVff1/Device2",
    "97PUAcUC5UYxLpBOLnC4yQjxiEf2_Device3": "97PUAcUC5UYxLpBOLnC4yQjxiEf2/Device3"
  },
  "Books": {
    "97PUAcUC5UYxLpBOLnC4yQjxiEf2_Device2": "97PUAcUC5UYxLpBOLnC4yQjxiEf2/Device2"
  }

}

So the above structure uses <uid>_<devicekey> as the keys and then has the path to that item under /devices as its value.

I recommend reading this great article on NoSQL data modeling.