mercredi 27 janvier 2021

How to get random child from Firebase Database in Go?

I have a Firebase database with the following structure:

{
  "School" : {
    "Class A" : {
      "Student K" : [ "Language1", "Language2" ],
      "Student L" : [ "Language1", "Language2", "Language3 ],
    },
    "Class B" : {
      "Student M" : [ "Language1", "Language2" ],
      "Student N" : [ "Language1", "Language3 ],
      "Student O" : [ "Language1", "Language2", "Language3 ],
    },
  },
}

Here all languages are different and none of them are same for any student.

Now I want to retrieve a random Student and Languages pair from this database. I have reference upto the Class node.

Currently I am retrieving all the children of School/Class and then storing them in a map. To get a random key, value pair from them I just traverse the map once using range to get an arbitrary pair.

My code looks like this:

q := constants.GlobalClient.NewRef("School/" + className)
result := make(map[string][]string)
lang, studName := "", ""

if err := q.Get(constants.GlobalCtx, &result); err != nil {
    return nil, err
}

var allLang []string
for key, value := range result {
    studName = key
    allLang = value
    break
}

But, this is not providing the amount of randomness I would want, so I want to just retrieve a random Student, Languages pair from the database query itself.

I am new to using firebase with Go and can't seem to find a solution for this.




Aucun commentaire:

Enregistrer un commentaire