I'm newbie to Firestore. Firestore docs says...
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.
Reference: https://firebase.google.com/docs/firestore/manage-data/add-data
So do I have to create key name as timestamp
in document? Or created
is suffice to fulfill above statement from Firestore documentation.
{ "created": 1534183990, "modified": 1534183990, "timestamp":1534183990 }
To query on this Firestore field, you need to convert the date to timestamp and then query. Store as new Date(). toISOString() i.e. "2021-07-25T17:56:40.373Z" but you won't be able to perform date range query on this.
firestore. Timestamp. A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.
If you want to use server generated value which would be better so you don't depend on device time, use this: Map<String, dynamic> data = { 'name': userName, 'userUID': userUIDglobal, 'time': FieldValue. serverTimestamp(), }; Firestore. instance .
To convert a Firestore date or timestamp to a JavaScript Date, we use firebase. firestore. Timestamp. fromDate to convert the a date to a Firestore timestamp.
firebase.firestore.FieldValue.serverTimestamp()
Whatever you want to call it is fine afaik. Then you can use orderByChild('created').
I also mostly use firebase.database.ServerValue.TIMESTAMP when setting time
ref.child(key).set({ id: itemId, content: itemContent, user: uid, created: firebase.database.ServerValue.TIMESTAMP })
Use firestore Timestamp class, firebase.firestore.Timestamp.now()
.
Since firebase.firestore.FieldValue.serverTimestamp()
does not work with add
method from firestore. Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With