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 1:

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

Solution 2:

Use firestore Timestamp class, firebase.firestore.Timestamp.now().

Since firebase.firestore.FieldValue.serverTimestamp() does not work with add method from firestore. Reference

Solution 3:

For Firestore

ref.doc(key).set({
  created: firebase.firestore.FieldValue.serverTimestamp()
})

Solution 4:

REALTIME SERVER TIMESTAMP USING FIRESTORE

import firebase from "firebase/app";

const someFunctionToUploadProduct = () => {

       firebase.firestore().collection("products").add({
                name: name,
                price : price,
                color : color,
                weight :weight,
                size : size,
                createdAt : firebase.firestore.FieldValue.serverTimestamp()
            })
            .then(function(docRef) {
                console.log("Document written with ID: ", docRef.id);
            })
            .catch(function(error) {
                console.error("Error adding document: ", error);
            });

}

All you need is to import 'firebase' and then call firebase.firestore.FieldValue.serverTimestamp() wherever you need it. Be careful with the spelling though, its "serverTimestamp()". In this example it provides the timestamp value to 'createdAt' when uploading to the firestore's product's collection.