我正在尝试使用 FirestoreDataConverter
将对象转换为 firestore 数据,但该转换器似乎仅适用于 addDoc
和 setDoc
操作,但是当尝试将它与 updateDoc
操作一起使用时,它不会触发 toFirestore
函数。
可重现的例子
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;
},
};
预期的控制台输出
Went through to-converter
Went through from-converter
Went through to-converter
实际控制台输出
Went through to-converter
Went through from-converter
这特别发生在 updateDoc
中。如果我改用 setDoc
,它会按预期工作。 updateDoc
根本不受支持吗?文档中似乎根本没有提到它。
https://firebase.google.com/docs/reference/node/firebase.firestore.FirestoreDataConverter
最佳答案
查看您的代码,您使用的是 Firestore Web 版本 9,它具有用于设置和更新数据的新语法。可以引用here以供引用。
您遇到的行为正在按预期工作。 updateDoc()
Web 版本 9 中的函数使用新的 UpdateData
进行类型检查并支持字段值的类型。
https://stackoverflow.com/questions/71437835/