firebasegoogle-cloud-firestore

Add timestamp in Firestore documents


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
}

Solution

  • 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 
    })