I have a firebase db with data like below:
I want to pull multiple records based on certain criteria. I've figured out how to pull a single record based on an ID using the method below:
ref := fbDB.NewRef("/Event/123")
event := data.EventData{}
if err := ref.Get(c, &event); err != nil {
// error handling stuff
}
This loads event
with the data I would expect. When I try to modify this code to select multiple records with the code below:
type EventResults struct {
Events []data.EventData
}
...
ref := fbDB.NewRef("/Event")
res := EventResults{}
if err := ref.Child("candy").OrderByValue().StartAt(350).Get(c, &res); err != nil {
//error handling stuff
}
res.Events
is always an empty array (and err
is nil).
Can anyone see what I'm doing wrong?
It's empty because when retrieving data you need to traverse the database and pass through each node.
In your case you have this:
ref.Child("candy");
Here ref
is referencing the node Event
and under Event
you have different Ids (123
, 789
), therefore you need to access these nodes before trying to access node candy
.
If you want to retrieve a list of candy
that are under Event
, then you should iterate inside the direct child of node Event
then you will be able to access node candy
.
Example:
f := firego.New("https://my-firebase-app.firebaseIO.com", nil)
var res map[string]interface{}
ref := fbDB.Ref("/Event")
if err := ref.OrderBy("candy").StartAt(3).Value(&res); err != nil {
}
You need to use the OrderBy
query to be able to retrieve result based on the value of of candy
. For example, in my code OrderBy("candy").StartAt(3)
, this query will give you a result where the value of candy starts with 3. candy :300
Check the docs:
This is basically what Peter posted above but the exact code I ended up using is below:
ref := fbDB.NewRef("/Event")
var res map[string]data.EventData
if err := ref.OrderByChild("candy").StartAt(350).Get(c, &res); err != nil {
//Error handling stuff
}