Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore order by time but sort by ID

I have been trying to figure out a way to query a list of documents where I have a range filter on one field and order by another field which of course isn't possible, see my other question: Order by timestamp with range filter on different field Swift Firestore

But is it possible to save documents with the timestamp as id and then it would sort by default? Or maybe hardcode an ID, then retrieve the last created document id and increase id by one for the next post to be uploaded?

This shows how the documents is ordered in the collection

This shows how the documents is ordered in the collection

Any ideas how to store documents so they are ordered by created at in the collection?

like image 234
user3116871 Avatar asked Apr 24 '18 21:04

user3116871


1 Answers

It will order by document ID (ascending) by default in Swift.

You can use .order(by: '__id__') but the better/documented way is with FieldPath documentID() I don't really know Swift but I assume that it's something like...

.order(by: FirebaseFirestore.FieldPath.documentID())

JavaScript too has an internal variable which simply returns __id__.

.orderBy(firebase.firestore.FieldPath.documentId())

Interestingly enough __name__ also works, but that sorts the whole path, including the collection name (and also the id of course).

like image 53
Ryan Taylor Avatar answered Oct 18 '22 23:10

Ryan Taylor