Firebase query not returning correct data - objective-c

I have the following data in Firebase:
- Info/
-2018-09-23-13-38-00-WhyNewYo
-2018-09-23-14-04-57-PompeoWe
-2018-09-23-14-10-32-FocusonE
-2018-09-23-14-39-00-SenPatty
-2018-09-23-14-40-30-Rebelatt
-2018-09-23-14-57-33-Piratesa
Each entries are created at a different time but I named them based on a specific title so I know which is the latest and it would be in alphabetical order when I view them in the Firebase console automatically.
When I wanted to query the latest 2 data (the last 2 based on the order shown above), but Firebase seems to return incorrect data and I am using the following code:
FIRDatabaseReference *dataRef = [[FIRDatabase database] reference];
dataRef = [dataRef child:[NSString stringWithFormat:#"/info"]];
[[[dataRef queryOrderedByValue] queryLimitedToLast:2] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *infoFromFirebase= snapshot.value;

When you query and observe FIRDataEventTypeValue, you get all matching nodes in a single snapshot. If you call snapshot.value the data is converted to a dictionary, and information on the order of the matching nodes is lost.
To maintain the order of the nodes, be sure to iterate over the children of the snapshot with for (FIRDataSnapshot* child in snapshot.children) { … }.

Related

How can i know if a relationship is fetched or not in neo4j?

For example I load an entity in the following way:
Movie m = session.load(Movie.class, id, 0); // load properties but not relationships
m.getActors(); // empty since depth was 0
A bit later in another method:
// Do I need to load it?
if (needsLoad(m) {
m = session.load(Movie.class, m.getId(), 1);
}
for (Actor a : m.getActors()) {
// ...
}
The only solution I've found is to load it every time.
Is there a better approach?
There is no API for accessing the session cache.
As a result it is not possible to get information about how deep the object graph got loaded.
I wonder how you get in the situation to need this.
The standard approach would be: load data from the database with the "right" depth, manipulate the data and save it back.
All within one transaction.

Merging data from different graphql resolvers in vue.js client side for simple outputting

I do query cars from an api with a single query but two resolvers (listing and listings)(hopefully resolver is the right name for it). One car I get by the id via listing and the other cars I get without filters by listings. The resolvers output the data i a little different structure on the server-side but I do get the same fields just at different „places“. I want to merge the structure in order to get a single array I can simply loop over in vue.js. For the apicalls I do use vue-apollo.
Couldn't find any information to merge data client-side inside graphqlqueries. All I found is about handling it serverside with resolvers but it's an api I do not own.
Is it possible with graphql or do I have to merge it inside my vuecomponent and if so what would be the best way to do so?
The output will be a grid of cars where I show the car of the week (requested by id) together with the newest cars of the regarding cardealer.
Full screenshot including response: https://i.imgur.com/gkCZczY.png
Stripped down example with just the id to show the problem:
query CarTeaser ($guid: String! $withVehicleDetails: Boolean!) {
search {
listing(guid: $guid){
details{
identifier{
id #for example: here I get the id under details->identifier
}
}
}
listings( metadata: { size: 2 sort:{ field: Age order: Asc}}) {
listings{
id #here it's right under listings
details{
…
}
}
}
}
}
}
Ideally you're right, it should be handled server-side, but if it's not your API the only solution is to manipulate the data on the client side, meaning in your component.
It's probably a lot simpler to leave the listings array untouched and to just merge the listing element with it, like this for instance:
// assuming 'search' holds the entire data queried from the api
const fullListing = [
// car of the week, data reformatted to have an identical structure as
// the 'other' cars
{
id: search.listing.details.identifier.id,
details: {
vehicle: search.listing.details.vehicle,
},
},
...search.listings.listings, // the 'other' cars
]

Firebase : How to query data with unknown key

I have this JSON Database:
I am trying to upload a given Score to a certain Post. My problem is that I don't know how to get for example the key, -KyCpxtBCXiHcEA49DNZ, which is generated in a different Class by:
self.randomkey = [[ref child:self.currentuser.uid] childByAutoId].key;
So far this is what I have:
self.randomkey = [[ref child:self.currentuser.uid] childByAutoId].key;
NSDictionary *updatescore = #{
#"Score": #"1", // For example
};
NSDictionary *childUpdates = #{[#"/Posts/" stringByAppendingString:self.randomkey]: updatescore};
What makes every post unique is actually the key I am trying to get. I've come across the queryEqualToValue which I could use to query the data inside that key.
Things I've tried:
Query to get all posts, and filter the ones that match with the UserID. Problem is that 1 user can have many posts
Run the code I mentioned. Issue is that it generated a new random key. This will result in a new branch under "Posts".
Find some node which can related both Posts and Users nodes, but as I said, 1 user can have many posts.
Can anyone point me in the right direction?. I am using Objective-C.

One To Many With Convenience Backpointer

I'd like to model a one-to-many relationship between users and checkIns on Parse.com. Additionally, I'd like a user to have a convenience pointer to it's lastCheckin, to avoid having to query checkIns to get a user's most recent checkIn. Using the following code, the user's lastCheckin column is always empty in the Data Browser:
PFUser *currentUser = [PFUser currentUser];
PFObject *checkIn = [PFObject objectWithClassName:#"CheckIn"];
checkIn[#"forUser"] = currentUser;
checkIn[#"foursquareID"] = selectedVenue[#"id"];
checkIn[#"name"] = selectedVenue[#"name"];
checkIn[#"location"] = [PFGeoPoint geoPointWithLatitude:[selectedVenue[#"location"][#"lat"] doubleValue]
longitude:[selectedVenue[#"location"][#"lng"] doubleValue]];
[checkIn saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
currentUser[#"lastCheckin"] = checkIn;
[currentUser saveInBackground];
}];
Removing the following line causes the User.lastCheckin to correctly point to the desired CheckIn in the Data Browser, but obviously this breaks the one-to-many linkage:
checkIn[#"forUser"] = currentUser;
Is there some way for me to get both the one-to-may relationship between Users and CheckIns, and a User.lastCheckIn pointer?
If you are setting the lastCheckin on the User each time you create a new CheckIn you can access that checkin easily by fetching the current user and including lastCheckin with includeKey.
http://blog.parse.com/2011/12/06/queries-for-relational-data/
To get all checkins for a user you can simply query the CheckIn class where the current user is equal to forUser. That is your 1 to many relationship. You do not need to maintain a relation of checkins on the User class since you have a pointer from each CheckIn instance back to the user as a pointer. When you set lastCheckin on the user instance you are not changing the property on older checkins.
Perhaps you are thinking this is like SQL with primary and foreign keys. I get confused by NoSQL since I have a SQL background. I am always learning to think like Parse and NoSQL. What I see above is all you need to query all checkins for a user and the last checkin for a user. You can also simply query all checkins for a user, limit result to 1 and sort it so the newest checkin is the first result. It should be quite fast on Parse.
You may also want to look into using Cloud Code. You could call a Cloud Code function and simply pass the parameters you need to create a new checkin and have all of this work done in Cloud Code. An After Save function could be used to update lastCheckin on the user.
http://www.parse.com/docs/js/symbols/Parse.Cloud.AfterSaveRequest.html
If you user on Cloud Code you can update how the data is managed without updating the iOS app.

Filtering NSFetchedResultsController results at runtime

What's the best way to implement runtime filtering of Core Data objects using NSFetchedResultsController?
For example, I want to be able to display all Record-entities in a RecordStore-entity, but also filter all Records in a RecordStore for some predefined critera, eg (ANY recordStore.records.count > 0).
I read that changing an NSFetchedResultsController's predicate after it has been created is bad. So should I store the fetched results in an NSArray that I can filter and use that as the UITableView's datasource, or should I create multiple NSFetchedResultsControllers?
You can re-fetch the data when you need to update. If the data itself changed, then you can just call fetch again. If your criteria changed, then set the predicate on your NSFetchedResultsController, and call fetch.
Create the NSFetchRequest instance, update request each time and perform fetch. Delete cache if you are using:
let shortDescriptor = NSSortDescriptor(key: key, ascending: ascending)
fetchedResultViewController.fetchRequest.sortDescriptors = [shortDescriptor]
NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: fetchedResultViewController.cacheName)
do {
try fetchedResultViewController?.performFetch()
} catch let error as NSError {
print("Error in fetch \(error)")
}
Read the apple document: https://developer.apple.com/reference/coredata/nsfetchedresultscontroller