如何从Firebase获取多个记录?

I have a firebase db with data like below: enter image description here

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?

2个回答

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:

https://godoc.org/gopkg.in/zabawaba99/firego.v1

douejuan9162
douejuan9162 好的,如果您使用的是上面的链接,请执行ref.OrderByChild(“ candy”)。StartAt(3).Get(&res)
一年多之前 回复
duanpei8853
duanpei8853 嗯,我没有使用firego软件包,但让我看看能否确定如何将其应用于内置库:godoc.org/firebase.google.com/go/db
一年多之前 回复
dongmei5168
dongmei5168 检查答案中的编辑内容,我也不知道golang,但是我编写的代码应该根据我进行的搜索工作
一年多之前 回复
douxuanwei1980
douxuanwei1980 因此,我真正想要的是获取糖果值在一定范围内的单个事件。 如何根据candy的值限制要提取的事件记录? 我知道ref.Child(“ candy”)是不正确的,但我不清楚我应该怎么做
一年多之前 回复

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
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐