I have a simple Firebase Realtime database that looks like this:
I created it with a PUT call using this as the body:
[{
"complete": false,
"editMode": false,
"title": "Mow the lawn",
"id": 26,
"note": "This is a note for 27"
},
{
"complete": true,
"editMode": false,
"title": "Feed the dog",
"id": 27,
"note": "This is a note for 27"
}
]
I want to create a REST GET call to get the first item based on the ID (26 in this case).
My rules look like this:
{
"rules": {
".read": true,
".write": true,
"todos": {
".indexOn": ["id"]
}
}
}
I tried:
https://<myid>.firebaseio.com/todos/26/id.json
but that returned null
because of course that dang '0' and '1' are there.
I can do this:
https://<myid>.firebaseio.com/todos/0.json
and that returns the first item, but when I do this:
https://<myid>.firebaseio.com/todos.json
the '0' and the '1' aren't returned, so how do I know to use them?
Do you understand my confusion?
What am I missing?
Firebase Realtime Database doesn't natively store arrays. Instead it stores the array elements in sequential keys, starting with "0"
.
When you request a location/query with sequential keys starting with "0"
through the REST API, Firebase returns the data as an array, which is what you see when you request todo.json
.
But you can address individual items in the array by their key, which is what you did by requesting todo/0.json
.
All of the above gets a single node by its complete and absolute path. But it seems that what you want is to retrieve a node by querying for the value of one of its properties. To do that, you'll need to use a query.
To get the item(s) with "id"
equal to 26
, you can perform the following query:
https://<myid>.firebaseio.com/todos.json?orderBy="id"&equalTo=26
Since there may be multiple child nodes under todos
with id
equal to 26
, this returns a list of such nodes. In the case of the JSON you shared:
{
"0": {
"complete": false,
"editMode": false,
"id": 26,
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With