How to sort a value inside a Firebase child for the rest?

In my firebase, I have several events, each with a header and a date string:

{ "events": { "-JscIDsctxSa2QmMK4Mv": { "date": "Friday, June 19, 2015", "title": "Event Two" }, "-Jswff0o9bWJeDmUoSA9": { "date": "Friday, June 12, 2015", "title": "Event One" }, "-JscIs_oMCJ9aT6-JWDg": { "date": "Monday, August 10, 2015", "title": "Event Three" } } } 

In my javascript code, I retrieve the children of events and click each header and date on the array, and then add it to the html page and display the content.

 var ref = new Firebase("https://demo.firebaseio.com/events"); var build = new Array(""); ref.orderByChild("date").once("value", function(snapshot) { snapshot.forEach(function(data) { var tmp = data.val(); eventMonth = tmp.date.split(" ")[1]; build.push('<h3>'+tmp.title+'</h3><p>Date: '+tmp.date+'</p>'); }); $("#event-content").append(build.join('')); 

orderByChild doesn't seem to work, how can I order events by date so that it can look something like this:

First Event: Friday, June 12, 2015

Second Event: Friday 19 June 2015

Stage Three: Monday, August 10, 2015

+4
source share
2 answers

Firebase does not have a date type, because JSON does not have it. Therefore, he does not know that dates are stored in these lines. To sort, you must save a primitive type that represents these dates and gives the desired sort order when comparing as a string or number.

For example: timestamp. This date is a JS date object, adds sortDate: date.getTime() to each object when it is saved.

 { "events": { "-JscIDsctxSa2QmMK4Mv": { "date": "Friday, June 19, 2015", "sortDate": 1434697200000, "title": "Event Two" }, "-Jswff0o9bWJeDmUoSA9": { "date": "Friday, June 12, 2015", "sortDate": 1434092400000, "title": "Event One" }, "-JscIs_oMCJ9aT6-JWDg": { "date": "Monday, August 10, 2015", "sortDate": 1439190000000, "title": "Event Three" } } } 

And then:

 ref.orderByChild("sortDate")... 
+4
source

you can get the ordered data from the Firebase database and then save it in an array, reverse the order if you want, and use the completion block to return all the objects.

 func fetchObjects(completion: @escaping ([Object])->()){ let reference = FIRDatabase.database().reference().child("firebaseObjects") reference.queryOrdered(byChild: "creationDate").observeSingleEvent(of: .value, with: {(snapshot) in guard var allObjects = snapshot.children.allObjects as? [FIRDataSnapshot] else {return} //Reversing the order of the array allObjects.reverse() var objects = [Object]() allObjects.forEach({ (snapshot) in guard let dictionary = snapshot.value as? [String: Any] else {return} let object = Object(dictionary: dictionary) objects.append(object) }) completion(objects) }) {(err) in print("Failed to fetch the objects with UID", err) } } 

Hope this helps.

0
source

All Articles