Flutter Firebase documents are randomly ordered - firebase

I made a simple chat app using Flutter. My app is functioning perfectly fine (getting and dumping data into firebase) but once my messages get into my database, they are randomly ordered resulting in my msgs getting displayed in a random order.
I have tried reversing the SnapshotQueue in my Flutter code but that did not help...

You will need to attach document names to your documents before uploading them.
I think you are experiencing this issue because your documents are being given Auto Ids.
Try using the current timestamp as the document name. this will help arrange documents in order according to time uploaded.
Firestore.instance.collection(CollectionName).document(Timestamp.now()).setData(messageMap);
i hope this is what you need. if not. Please share your code that uploads the message to database.

Add a field like datePublished = DateTime.now() to each message document as
it gets created to
store the timestamp of when the message was created
Then you can use datePublished field to order your documents of your QuerySnapshot like this:
QuerySnapshot snapshot = await collection.orderBy('datePublished', descending: true).get();
now your messages are arranged in chronological order from the latest
to earliest.

Related

Check if item is not in a Firebase document

I have a field in my Firestore documents that happens to be an array of user IDs, this field is called "tempID", I want to run a query that return all documents that do not contain a particular user ID stored in "tempID". I did my research and found two useful articles.
Firebase check if item is not in array in Flutter
I tried what was suggested in this link but I am not getting desired outcome.
https://firebase.google.com/docs/firestore/query-data/queries#dart_8
I read official documentation from this link but still have not been able to implement desired outcome.

Cloud firestore - Order by nested data

I am new to Firebase cloud firestore. My database structure looks something like in the picture below. So, basically I have got a document for 'Liked' which tracks the timestamp at which user has liked the content. It has got 'chapter' as subcollection and inside each chapter there are sub-chapters which has the actual timestamp. Now I want to retrieve all the liked data ordered by the timestamp. I am not sure how can I achieve this!
You may use orderBy() to specify the sort order for your data like shown in the following example:
db.collection("liked").orderBy('timestamp').get()
I would also suggest you to follow this doc, it demostrates how to set up Cloud Firestore, add, read data and secure data.
UPDATE
I created the following database to replicate your scenario:
reprod(collections)/
test1(document)/
liked(collections)/
0(document)/
type(filed)
To stream the timestamps in ascending order I iterated manually to the doc and fetched the data ordered by timestamp:
reprod = db.collection(u'reprod').document(u'test1').collection(u'liked')
timestamps = reprod.stream()
for doc in timestamps:
print(f'{doc.id} => {doc.to_dict()}')
To do that I used the Firestore documentation on how to retrieve data and how to order data.

increment document id by timestamp in firestore

My cloud firestore database has an "orders" collection and in HTML I have a 'save' button to add document(s) into that "orders" collection upon clicking. Now, using add will assign auto-generated ID for each document.
What if I want to customise such ID by timestamp? So that the document created yesterday will be assigned an index as '1', and the following document created will be '2', etc...
What you're trying to do is not compatible with the way Cloud Firestore was designed. Firestore will not assign monotonically increasing numbers for document IDs. This just doesn't scale massively as required by Firestore and would introduce performance bottlenecks.
If you want to be able to sort documents by timestamp, the best strategy is to add a timestamp field to each document, then use that field in an ordered query.
Note that you could try to write a lot of code to get this done the way you want, but you are MUCH better off accepting the random IDs and using fields to filter and order data.
in some case, when you need to save several docs in different collection due to an event occurs, it's better to same all docs with same id in different collections with single firestore server's timestamp. you get the timestamp like below:
const admin = require('firebase-admin')
const ts = admin.firestore.Timestamp.now().toMillis().toString()
by doing this, when you need to read all those docs, you only need to query once to get timestamp, then read all other doc by timestamp directly.
it should be faster than query the timestamp inside document fields for each collections

How to sort firebase documents by the size of a list in Flutter?

Could someone explain to me how I can order documents on Firebase by the size of a list?
I have this 'rec' list on several items, but I can only sort it as:
body: FutureBuilder<QuerySnapshot>(
future: Firestore.instance
.collection("products")
.document(snapshot.documentID)
.collection("items")
.orderBy("rec")
.getDocuments(),
https://i.stack.imgur.com/3yV9D.png
You need to add a recSize key to your documents and a firebase function that recalculates the size of your list every time the list changes. Then order using recSize.
Firestore does not provide us with metadata, hence in order to get the size of a document stored in a collection you can proceed with one of the following:
As Henok pointed out, use a field to store the current size of the document and use it to sort your data on the back-end side.
Download your unsorted documents and sort them on the client according to their size.
Please check out this similar thread which you may found useful in both cases.

how to add documents to bottom of the document column in Cloud Firestore through the Firebase console

I'm adding data to cloud Firestore through the Firebase Console. I've added a collection and the corresponding documents and fields. When I click on " ADD DOCUMENT", the new document appears randomly (as far as I can make out) on the document column. I want the newly generated document to appear at the bottom of the document column. The order matters when viewing the data on the app. The data is used in a recycler view. Is this possible?
Cloud Firestore does not order documents in the same way as the RTDB. Auto IDs are not time related. You will need to add a timestamp field and order your data by this field.
You can read about this here.
Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud
Firestore auto-generated IDs do not provide any automatic ordering. If
you want to be able to order your documents by creation date, you
should store a timestamp as a field in the documents.
I used Firestore's "set" method instead of "add" and used a numerical date string; it is automatically adding and listing them in numerical order.
// Swift
let dataToSave: [String: Any] = ["example": "example"]
collectionRef.document(dateString).setData(dataToSave) { (error) in
}
If you use the "add" method, the key will be automatically generated with a random alphanumeric string.
The collection orders everthing alphanumerically, so setting your documents using keys of numbers or letters, exclusively, will allow for an ordered list.

Resources