Getting nested children from Firebase Database - ios

I am attempting to populate a table view with values from my Firebase database. I was able to use queryOrdered on the root of my database to get the children I required, as seen here:
func oneTimeInit() {
databaseRef?.queryOrdered(byChild: "Seasons").observe(.value, with:
{ snapshot in
for item in snapshot.children {
self.seasons.append(Season( snapshot: item as! DataSnapshot))
}
self.seasonsTableView.reloadData()
})
}
But now I am trying to get the children of the next node in my database. I tried to do this by calling queryOrdered on the child of the root but I'm not getting any data. Here is my code:
func oneTimeInit() {
databaseRef?.child("Seasons").queryOrdered(byChild: season.name).observe(.value, with:
{ snapshot in
for item in snapshot.children {
print("ITEM VALUE: \(item)")
self.races.append(Race(snapshot: item as! DataSnapshot))
}
self.racesTableView.reloadData()
})
}
The Database contains, at its highest level, Cross Country Seasons, which each contain Cross Country Races, which each contain results. Im able to populate the Seasons table but not the Races table, and so on.
Heres the Json structure of my database:
{
"Seasons" : {
"XC 2018" : {
"NCAA DI West Regional" : {
"Men" : {
"Results" : {
"Aaron BRUMBAUGH" : {
"finishTime" : "31:59.0",
"lapTimes" : [ "5:05.1", "10:43.3", "11:07.1", "5:03.5" ],
"name" : "Aaron BRUMBAUGH",
"position" : "118",
"splitTimes" : [ "5:05.1", "15:48.4", "26:55.5", "31:59.0" ],
"team" : "Santa Clara",
"year" : "SR"
},
"Addison DEHAVEN" : {
"finishTime" : "29:47.8",
"lapTimes" : [ "4:58.2", "10:14.0", "10:04.1", "4:31.5" ],
"name" : "Addison DEHAVEN",
"position" : "7",
"splitTimes" : [ "4:58.2", "15:12.2", "25:16.3", "29:47.8" ],
"team" : "Boise State",
"year" : "SR"
},
"Ahmed MUHUMED" : {
"finishTime" : "30:08.1",
"lapTimes" : [ "4:58.6", "10:14.6", "10:08.5", "4:46.4" ],
"name" : "Ahmed MUHUMED",
"position" : "29",
"splitTimes" : [ "4:58.6", "15:13.2", "25:21.7", "30:08.1" ],
"team" : "Boise State",
"year" : "SO"
},
As of now there is only one "Season" (XC 2018) with one "Race" (NCAA D1 West Regional). I'm trying to get a reference to all of the "Races" under the "Season" XC 2018.
The variable season.name would contain the value "XC 2018". With my second one time init I am trying to look at the children of "XC 2018".

Related

How do I compare two nested documents using mongo_dart

Here is my database entry structure, it has a nested document called friends, I want to compare two different _id's friends list in dart using mongo_dart
{
"_id" : ObjectId("60ae06074e162995281b4666"),
"email" : "one#one.com",
"emailverified" : false,
"username" : "one#one.com",
"displayName" : "complete n00b",
"phonenumber" : "",
"dob" : "",
"points" : 0,
"friends" : [
{
"username" : "three#one.com",
"sent" : ISODate("2021-05-26T10:01:30.616Z")
},
{
"username" : "six#one.com",
"sent" : ISODate("2021-05-26T10:43:16.822Z")
}
]
}
Here is my code, but I am not getting any returns
Future<Map> commonFriends(store, myObjectId, theirObjectId) async {
var commonList = await store.aggregate([
{
'\$project': {
'friends': 1,
'commonToBoth': {
'\$setIntersection': [
{'_id': myObjectId, 'friends': '\$username'},
{'_id': theirObjectId, 'friends': '\$username'}
]
},
}
}
]);
return commonList;
}
I am getting an error from db.dart which is apart of mongo_dart package. The error is "Exception has occurred.
Map (4 items)"

firebase database filtering is not working. Need some assistance

I have a simple test database that I cant get to filter. I indexed the category in the rules:
"questions":{
".indexOn": ["category"]
},
My filter for the quiz app:
/questions.json?orderBy="category"&equalTo="Basics"&print=pretty
and my database:
"-MKoucSP33zm4jC43AnY" : {
"title" : {
"answers" : [ {
"score" : 30,
"text" : "Pineapple"
}, {
"score" : 5,
"text" : "Ham"
}, {
"score" : 20,
"text" : "Yogurt"
}, {
"score" : 10,
"text" : "Crab"
} ],
"category" : "Basics",
"questionId" : "101",
"questionImage" : "",
"questionLink" : "",
"questionText" : "What topping do you like the best on pizza?"
}
}
The category property is nested under the title node, so the property you need to order/filter on is title/category:
/questions.json?orderBy="title/category"&equalTo="Basics"&print=pretty
You'll also need to update your index definition for that path, so:
"questions": { ".indexOn": "title/category" }
Working example: https://stackoverflow.firebaseio.com/64596200/questions.json?orderBy="title/category"&equalTo="Basics"

Ignoring Firebase child

How could I query this data in this way:
I would like to ignore the CurrentSubAdministrativeArea child and iterate every each sub child and find the right userKey
Actually I'm using this code, that isnt working:
self.ref.child("Ads").child("CurrentSubAdministrativeArea")
/*HERE I would like to ignore the childs*/
.queryOrdered(byChild: "userKey").queryEqual(toValue: uid).observeSingleEvent(of:.value, with: { (snapshot) in
--
{
"Ads" : {
"CurrentSubAdministrativeArea" : {
"Mantova" : {
"-L7ymBmmbHkNfhBRte9F" : {
"cost" : 200,
"date" : 1527256922000,
"info" : "Test",
"maxLimit" : 100,
"minLimit" : 10,
"personBadType" : [ "abitudinaria", "antipatica" ],
"personGoodType" : [ "simpatica", "felice" ],
"subAdministrativeArea" : "Mantova",
"title" : "Mantova Test",
"url" : "https://firebasestorage.googleapis.com/v0/b/team-34540.appspot.com/o/Mantova%20Test?alt=media&token=3a81ed1c-ecd6-4dc0-bd7c-45e093ce8188",
"userKey" : "OsJRc98sqxPx70iqxFtoqerMzHH2",
"via" : "viale dei test"
}
},
"Milano" : {
"-L6qywMC6nxi0fJNMHba" : {
"cost" : 454,
"date" : 1528298580000,
"info" : "Di pollo",
"maxLimit" : 100,
"minLimit" : 10,
"personBadType" : [ "abitudinaria", "antipatica" ],
"personGoodType" : [ "simpatica", "felice" ],
"subAdministrativeArea" : "Milano",
"title" : "Pollo 2",
"url" : "https://firebasestorage.googleapis.com/v0/b/team-34540.appspot.com/o/Pollo?alt=media&token=fc6a3ec8-5f9a-4347-bdad-2d9715af784d",
"userKey" : "OsJRc98sqxPx70iqxFtoqerMzHH2",
"via" : "viale test"
}
}
}
}
}
You could denormalize your data in such a way your query is easy to build and execute.
Together with the data structure you already have you would have another node (ie. another data structure) like
{
"AdsByUsers" : {
"OsJRc98sqxPx70iqxFtoqerMzHH2": {
"Mantova",
"Milano",
...
},
"abcde88qxPx70iqxFtoqerMzKh5": {
"Firenze",
...
}
With NoSQL database you should not hesitate to duplicate data in such a way your queries are easy and fast to execute.

Query object in child array

I am trying to use a query to retrieve data of student who are only 4 years old from my database but i cant figure out how to use Firebase to query the age (The array in each child).
{
"student" : {
"-Kv2RVDDsI-v6V7g_LBn" : [ {
"name" : "sam",
"age" : "6"
}, {
"name" : "tom",
"age" : "4"
}
],
"-hguyu-v6V7g_LBn" : [ {
"name" : "Tim",
"age" : "12"
}, {
"name" : "tom",
"age" : "4"
}
]
}
}
This is my code but it does no return anything.
ref.child("student").queryOrdered(byChild: "age").queryEqual(toValue: 4).observe(.childAdded, with: { (snapshot) in
let value = snapshot.value
print(value)
}) { (error) in
print(error.localizedDescription)
}
However, if i remove the queryOrdered(byChild: "age") it works.
Thanks.
You are referencing "Student" when actually your JSON database format child path name is "Students".
Also make sure that you are querying by key. Refer to the Firebase documentation to see how to query by key. I don't understand your structure though why you have 2 children per key.
Why not have a new key for each child?

Firebase query with queryOrderedByKey().queryLimitedToLast(10) does not return one of the last 10 items

I am trying to load the last 10 products that have been added to the all_products table in firebase.
I run the following query with version 3.2.0 of the firebase SDK:
let fbRef = FIRDatabase.database().reference().child("products_all").queryOrderedByKey().queryLimitedToLast(10).observeSingleEventOfType(.Value, withBlock: { snapshot in
for item in snapshot.children {
let keyString = (item as! FIRDataSnapshot).key
However, the items that get returned are not the last 10 items in this table. I have about 1017 products in this table and the first item that gets returned in this query is item 973, while it should be item 1008.
My firebase looks like this (I used childByAutoId to add the products):
{
"products_all" : {
"-KFOiZDrbR4eq4fXSdMZ" : {
"affiliate_url" : "https://some.link.com",
"description" : "product description",
"image_url" : "https://image.url.com/firstImage.jpg",
"images" : [ "https://image.url.com/firstImage.jpg", "https://image.url.com/secondImage.jpg" ],
"merchant" : "merchant.com",
"price_usd" : "100.00",
"title" : "product title"
},
...,
"-KFtOmT_Hq-48chbHh7I" : {
"affiliate_url" : "https://another.link.com",
"description" : "another product description",
"image_url" : "https://image.link.com/anotherImage.jpg",
"images" : [ "https://image.link.com/anotherImage.jpg" ],
"merchant" : "anothermerchant.com",
"original_currency" : "GBP",
"original_price" : "255",
"price_usd" : "364.65",
"product_category" : "Bracelet",
"external_product_id" : "Anothermerchant-123",
"title" : "another product title"
},
...,
"-KFtOmTlcb5-PTQ6kTv8" : {
"affiliate_url" : "https://last.product.com",
"description" : "last product description",
"image_url" : "https://last.product.com/image.jpg",
"images" : [ "https://last.product.com/image.jpg" ],
"merchant" : "anothermerchant.com",
"original_currency" : "GBP",
"original_price" : "179",
"price_usd" : "268.5",
"product_category" : "Bracelet",
"scraped_product_id" : "anothermerchant-493",
"title" : "last product title"
}
}
}
EDIT: Also, the last element in the batch of 10 is number 992 - so the 10 items are neither in the last 10, nor are their all 'neighbours'.
First keys that were included:
-KFtOmT_Hq-48chbHh7I
-KFtOmT_Hq-48chbHh7J
-KFtOmT_Hq-48chbHh7K
Subsequent keys that were skipped:
-KFtOmT0Qj3mrCTlxOfj
-KFtOmT1jouJgm8x_Mi7
-KFtOmT4GUpXtd9Y90sq
-KFtOmT4GUpXtd9Y90sr
-KFtOmT57vidxDl_jpj_
-KFtOmT57vidxDl_jpja
-KFtOmT9yuy-1G8WBrsE
Then some keys were included and others again excluded, the 'coverage' is patchy.

Resources