Hyungju Moon
Hyungju Moon

Reputation: 141

Using firestore meta createTime and updateTime

I've realized that there is private meta information "createTime" and "updateTime" in every Firestore document.

{
 ...

  "_createTime": {
    "_seconds": 1657794552,
    "_nanoseconds": 15469000
  },
  "_updateTime": {
    "_seconds": 1657794552,
    "_nanoseconds": 200837000
  }
}

Simply, Is there any reason I have to use my own "createdAt" and "updatedAt" fields? May I use these already existing "_updateTime,_createTime" values in my app logic?

Upvotes: 2

Views: 2002

Answers (2)

Zelf
Zelf

Reputation: 2250

As of June 2023, create_time and update_time are no longer available on doc. You can access doc.createTime and doc.updateTime, which are of Firestore Timestamp type.

From firestore.d.ts. Also see this Firestore doc.

  /**
   * A `QueryDocumentSnapshot` contains data read from a document in your
   * Firestore database as part of a query. The document is guaranteed to exist
   * and its data can be extracted with `.data()` or `.get(<field>)` to get a
   * specific field.
   *
   * A `QueryDocumentSnapshot` offers the same API surface as a
   * `DocumentSnapshot`. Since query results contain only existing documents, the
   * `exists` property will always be true and `data()` will never return
   * 'undefined'.
   */
  export class QueryDocumentSnapshot<
    T = DocumentData
  > extends DocumentSnapshot<T> {
    private constructor();

    /**
     * The time the document was created.
     */
    readonly createTime: Timestamp;

    /**
     * The time the document was last updated (at the time the snapshot was
     * generated).
     */
    readonly updateTime: Timestamp;

    /**
     * Retrieves all fields in the document as an Object.
     *
     * @override
     * @return An Object containing all fields in the document.
     */
    data(): T;
  }

Upvotes: 1

Sathi Aiswarya
Sathi Aiswarya

Reputation: 2915

I don't believe you can query by metadata,you can only access it. As mentioned in this stackoverflow Answer, There is no way to query on the metadata that Firestore automatically maintains. If you need to query then you will need to add a field with that value to the document's data.

Firebase Firestore provides create_time and update_time timestamps in v1, if you only need output.Have a look at this document

create_time

  • Output only. The time at which the document was created.

  • This value increases monotonically when a document is deleted then recreated. It can also be compared to values from other documents and the read_time of a query.

update_time

  • Output only. The time at which the document was last changed.

  • This value is initially set to the create_time then increases monotonically with each change to the document. It can also be compared to values from other documents and the read_time of a query.

Upvotes: 2

Related Questions