eosca
eosca

Reputation: 53

Could I get 'creationTime' when I create a new document in Firestore (instead of using 'documentRef.get()' after creation and thus avoid that reading?

Goal: get the creation time of a new Firestore document in the document creation process

First I create a new document with the corresponding data newDocumentData and a field creationTime with the creation time, as shown below:

const newDocumentRef = await collectionRef.add({
  ...newDocumentData,
  creationTime: firebase.firestore.FieldValue.serverTimestamp()
})

Then, I need the creationTime, and I follow like this...

const document = await newDocumentRef.get()
if (document.exists) {
  const documentData = document.data()
}

...to finally get my documentData.creationTime.

My question is: Is there any way to get creationTime with newDocumentRef in the first step and, therefore, avoiding the rest of the process?

Thank you!

Upvotes: 1

Views: 651

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83153

No, it is not possible with the Client SDKs, "to get the value of creationTime in the first step". FieldValue.serverTimestamp() returns a sentinel value that tells the server to assign a server-generated timestamp in the written data.

In other words the exact value for creationTime will be calculated by the server, and if you want to get this value, you need to query the database for it.


Note that, on the other hand, with the Firestore REST API, when you create a document, you get back (i.e. through the API endpoint response) a Document object that contains, among others, a createTime field.

Upvotes: 4

Related Questions