The Firebase JS SDK is now in BETA!
This EAP site is no longer maintained. See the official Firebase Documentation site for the latest documentation and information about the Firebase JS SDK.

Home > @firebase/firestore > / > FirestoreDataConverter

FirestoreDataConverter interface

Converter used by withConverter() to transform user objects of type T into Firestore data.

Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.

Signature:

export declare interface FirestoreDataConverter<T> 

Example

class Post {
  constructor(readonly title: string, readonly author: string) {}

  toString(): string {
    return this.title + ', by ' + this.author;
  }
}

const postConverter = {
  toFirestore(post: Post): firebase.firestore.DocumentData {
    return {title: post.title, author: post.author};
  },
  fromFirestore(
    snapshot: firebase.firestore.QueryDocumentSnapshot,
    options: firebase.firestore.SnapshotOptions
  ): Post {
    const data = snapshot.data(options)!;
    return new Post(data.title, data.author);
  }
};

const postSnap = await firebase.firestore()
  .collection('posts')
  .withConverter(postConverter)
  .doc().get();
const post = postSnap.data();
if (post !== undefined) {
  post.title; // string
  post.toString(); // Should be defined
  post.someNonExistentProperty; // TS error
}

Methods

Method Description
fromFirestore(snapshot, options) Called by the Firestore SDK to convert Firestore data into an object of type T. You can access your data by calling: snapshot.data(options).
toFirestore(modelObject) Called by the Firestore SDK to convert a custom model object of type T into a plain JavaScript object (suitable for writing directly to the Firestore database). To use set() with merge and mergeFields, toFirestore() must be defined with Partial<T>.
toFirestore(modelObject, options) Called by the Firestore SDK to convert a custom model object of type T into a plain JavaScript object (suitable for writing directly to the Firestore database). Used with setDoc(), and with merge:true or mergeFields.