How does one use the FirestoreDataConverter with update?

Viewed 852

I'm trying to use the FirestoreDataConverter to transform objects to firestore data but it seems that the converter only works for the addDoc and setDoc operations but when trying to use it with an updateDoc operation, it doesn't trigger the toFirestore function.

Reproducible example

interface Post {
  author: string;
  content: string;
}

async function addAndUpdatePost() {
  const colRef = collection(firestore, 'posts')
    .withConverter(postConverter);
  const post: Post = { author: 'Author', content: 'Content'};
  const docRef = doc(colRef);
  await setDoc(docRef, post);                      // Triggers toFirestore function
  const addedPost = (await getDoc(docRef)).data(); // Triggers fromFirestore function
  if (!addedPost) return;
  await updateDoc(docRef, addedPost)               // Does NOT trigger toFirestore function
}

const postConverter: FirestoreDataConverter<Post> = {
  toFirestore(post: Post): DocumentData {
    console.log("Went through to-converter");
    return { ...post};
  },

  fromFirestore(docSnap: QueryDocumentSnapshot): Post {
    console.log("Went through from-converter")
    return docSnap.data() as Post;
  },
};

Expected console output

Went through to-converter
Went through from-converter
Went through to-converter

Actual console output

Went through to-converter
Went through from-converter

This happens specifically with updateDoc. If I use setDoc instead, it works as expected. Is updateDoc simply not supported? Doesn't seem like it's mentioned at all in the docs. https://firebase.google.com/docs/reference/node/firebase.firestore.FirestoreDataConverter

1 Answers

Looking at your code, you're using Firestore Web Version 9 that has the new syntax for setting and updating the data. You may refer here for proper reference.

The behavior that you encountered is working as intended. The updateDoc() function in Web Version 9 uses a new UpdateData type that does the type checking and supports Field Values.

Related